forked from intellij-rust/intellij-rust
-
Notifications
You must be signed in to change notification settings - Fork 0
/
TypeInference.kt
1605 lines (1421 loc) · 65.8 KB
/
TypeInference.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.types.infer
import com.intellij.openapi.util.Computable
import com.intellij.psi.PsiElement
import com.intellij.psi.util.CachedValueProvider
import com.intellij.psi.util.CachedValuesManager
import com.intellij.psi.util.PsiModificationTracker
import com.intellij.util.containers.isNullOrEmpty
import org.jetbrains.annotations.TestOnly
import org.rust.lang.core.psi.*
import org.rust.lang.core.psi.ext.*
import org.rust.lang.core.resolve.ImplLookup
import org.rust.lang.core.resolve.SelectionResult
import org.rust.lang.core.resolve.StdKnownItems
import org.rust.lang.core.resolve.ref.MethodCallee
import org.rust.lang.core.resolve.ref.resolveFieldLookupReferenceWithReceiverType
import org.rust.lang.core.resolve.ref.resolveMethodCallReferenceWithReceiverType
import org.rust.lang.core.resolve.ref.resolvePath
import org.rust.lang.core.stubs.RsStubLiteralType
import org.rust.lang.core.types.BoundElement
import org.rust.lang.core.types.TraitRef
import org.rust.lang.core.types.selfType
import org.rust.lang.core.types.ty.*
import org.rust.lang.core.types.ty.Mutability.IMMUTABLE
import org.rust.lang.core.types.ty.Mutability.MUTABLE
import org.rust.lang.core.types.type
import org.rust.lang.utils.RsDiagnostic
import org.rust.openapiext.Testmark
import org.rust.openapiext.forEachChild
import org.rust.openapiext.recursionGuard
import org.rust.stdext.singleOrFilter
import org.rust.stdext.singleOrLet
import org.rust.stdext.zipValues
fun inferTypesIn(element: RsInferenceContextOwner): RsInferenceResult {
val items = StdKnownItems.relativeTo(element)
val lookup = ImplLookup(element.project, items)
return recursionGuard(element, Computable { lookup.ctx.infer(element) })
?: error("Can not run nested type inference")
}
/**
* [RsInferenceResult] is an immutable per-function map
* from expressions to their types.
*/
class RsInferenceResult(
private val bindings: Map<RsPatBinding, Ty>,
private val exprTypes: Map<RsExpr, Ty>,
private val resolvedPaths: Map<RsPathExpr, List<RsElement>>,
private val resolvedMethods: Map<RsMethodCall, List<RsFunction>>,
private val resolvedFields: Map<RsFieldLookup, List<RsElement>>,
val diagnostics: List<RsDiagnostic>
) {
fun getExprType(expr: RsExpr): Ty =
exprTypes[expr] ?: TyUnknown
fun getBindingType(binding: RsPatBinding): Ty =
bindings[binding] ?: TyUnknown
fun getResolvedPath(expr: RsPathExpr): List<RsElement> =
resolvedPaths[expr] ?: emptyList()
fun getResolvedMethod(call: RsMethodCall): List<RsFunction> =
resolvedMethods[call] ?: emptyList()
fun getResolvedField(call: RsFieldLookup): List<RsElement> =
resolvedFields[call] ?: emptyList()
override fun toString(): String =
"RsInferenceResult(bindings=$bindings, exprTypes=$exprTypes)"
@TestOnly
fun isExprTypeInferred(expr: RsExpr): Boolean =
expr in exprTypes
}
/**
* A mutable object, which is filled while we walk function body top down.
*/
class RsInferenceContext(
val lookup: ImplLookup,
val items: StdKnownItems
) {
val fulfill: FulfillmentContext = FulfillmentContext(this, lookup)
private val bindings: MutableMap<RsPatBinding, Ty> = HashMap()
private val exprTypes: MutableMap<RsExpr, Ty> = HashMap()
private val resolvedPaths: MutableMap<RsPathExpr, List<RsElement>> = HashMap()
private val resolvedMethods: MutableMap<RsMethodCall, List<RsFunction>> = HashMap()
private val resolvedFields: MutableMap<RsFieldLookup, List<RsElement>> = HashMap()
private val pathRefinements: MutableList<Pair<RsPathExpr, TraitRef>> = mutableListOf()
private val methodRefinements: MutableList<Pair<RsMethodCall, TraitRef>> = mutableListOf()
val diagnostics: MutableList<RsDiagnostic> = mutableListOf()
private val intUnificationTable: UnificationTable<TyInfer.IntVar, TyInteger> = UnificationTable()
private val floatUnificationTable: UnificationTable<TyInfer.FloatVar, TyFloat> = UnificationTable()
private val varUnificationTable: UnificationTable<TyInfer.TyVar, Ty> = UnificationTable()
private val projectionCache: ProjectionCache = ProjectionCache()
private class CombinedSnapshot(vararg val snapshots: Snapshot) : Snapshot {
override fun rollback() = snapshots.forEach { it.rollback() }
override fun commit() = snapshots.forEach { it.commit() }
}
fun startSnapshot(): Snapshot = CombinedSnapshot(
intUnificationTable.startSnapshot(),
floatUnificationTable.startSnapshot(),
varUnificationTable.startSnapshot(),
projectionCache.startSnapshot()
)
inline fun <T> probe(action: () -> T): T {
val snapshot = startSnapshot()
try {
return action()
} finally {
snapshot.rollback()
}
}
fun infer(element: RsInferenceContextOwner): RsInferenceResult {
if (element is RsFunction) {
val fctx = RsFnInferenceContext(this, element.returnType)
fctx.extractParameterBindings(element)
element.block?.let { fctx.inferFnBody(it) }
} else {
val (retTy, expr) = when (element) {
is RsConstant -> element.typeReference?.type to element.expr
is RsArrayType -> TyInteger.USize to element.expr
is RsVariantDiscriminant -> TyInteger.ISize to element.expr
else -> error("Type inference is not implemented for PSI element of type " +
"`${element.javaClass}` that implement `RsInferenceContextOwner`")
}
if (expr != null) {
RsFnInferenceContext(this, retTy ?: TyUnknown).inferLambdaBody(expr)
}
}
fulfill.selectWherePossible()
exprTypes.replaceAll { _, ty -> fullyResolve(ty) }
bindings.replaceAll { _, ty -> fullyResolve(ty) }
performPathsRefinement(lookup)
return RsInferenceResult(bindings, exprTypes, resolvedPaths, resolvedMethods, resolvedFields, diagnostics)
}
private fun performPathsRefinement(lookup: ImplLookup) {
for ((path, traitRef) in pathRefinements) {
val fnName = resolvedPaths[path]?.firstOrNull()?.let { (it as? RsFunction)?.name }
lookup.select(resolveTypeVarsIfPossible(traitRef)).ok()
?.impl?.members?.functionList?.find { it.name == fnName }
?.let { resolvedPaths[path] = listOf(it) }
}
for ((call, traitRef) in methodRefinements) {
val fnName = resolvedMethods[call]?.firstOrNull()?.name
lookup.select(resolveTypeVarsIfPossible(traitRef)).ok()
?.impl?.members?.functionList?.find { it.name == fnName }
?.let { resolvedMethods[call] = listOf(it) }
}
}
fun getExprType(expr: RsExpr): Ty {
return exprTypes[expr] ?: TyUnknown
}
fun isTypeInferred(expr: RsExpr): Boolean {
return exprTypes.containsKey(expr)
}
fun getBindingType(binding: RsPatBinding): Ty {
return bindings[binding] ?: TyUnknown
}
fun getResolvedPaths(expr: RsPathExpr): List<RsElement> {
return resolvedPaths[expr] ?: emptyList()
}
fun writeExprTy(psi: RsExpr, ty: Ty) {
exprTypes[psi] = ty
}
fun writeBindingTy(psi: RsPatBinding, ty: Ty) {
bindings[psi] = ty
}
fun writePath(path: RsPathExpr, resolved: List<BoundElement<RsElement>>) {
resolvedPaths[path] = resolved.map { it.element }
}
fun writeResolvedMethod(call: RsMethodCall, resolvedTo: List<RsFunction>) {
resolvedMethods[call] = resolvedTo
}
fun writeResolvedField(lookup: RsFieldLookup, resolvedTo: List<RsElement>) {
resolvedFields[lookup] = resolvedTo
}
fun registerPathRefinement(path: RsPathExpr, traitRef: TraitRef) {
pathRefinements.add(Pair(path, traitRef))
}
fun registerMethodRefinement(path: RsMethodCall, traitRef: TraitRef) {
methodRefinements.add(Pair(path, traitRef))
}
fun reportTypeMismatch(expr: RsExpr, expected: Ty, actual: Ty) {
diagnostics.add(RsDiagnostic.TypeError(expr, expected, actual))
}
fun canCombineTypes(ty1: Ty, ty2: Ty): Boolean {
return probe { combineTypesResolved(shallowResolve(ty1), shallowResolve(ty2)) }
}
fun combineTypesIfOk(ty1: Ty, ty2: Ty): Boolean {
return combineTypesIfOkResolved(shallowResolve(ty1), shallowResolve(ty2))
}
private fun combineTypesIfOkResolved(ty1: Ty, ty2: Ty): Boolean {
val snapshot = startSnapshot()
val res = combineTypesResolved(ty1, ty2)
if (res) {
snapshot.commit()
} else {
snapshot.rollback()
}
return res
}
fun combineTypes(ty1: Ty, ty2: Ty): Boolean {
return combineTypesResolved(shallowResolve(ty1), shallowResolve(ty2))
}
private fun combineTypesResolved(ty1: Ty, ty2: Ty): Boolean {
return when {
ty1 is TyInfer.TyVar -> combineTyVar(ty1, ty2)
ty2 is TyInfer.TyVar -> combineTyVar(ty2, ty1)
else -> when {
ty1 is TyInfer -> combineIntOrFloatVar(ty1, ty2)
ty2 is TyInfer -> combineIntOrFloatVar(ty2, ty1)
else -> combineTypesNoVars(ty1, ty2)
}
}
}
private fun combineTyVar(ty1: TyInfer.TyVar, ty2: Ty): Boolean {
when (ty2) {
is TyInfer.TyVar -> varUnificationTable.unifyVarVar(ty1, ty2)
else -> {
val ty1r = varUnificationTable.findRoot(ty1)
val isTy2ContainsTy1 = ty2.visitWith(object : TypeVisitor {
override fun invoke(ty: Ty): Boolean = when {
ty is TyInfer.TyVar && varUnificationTable.findRoot(ty) == ty1r -> true
ty.hasTyInfer -> ty.superVisitWith(this)
else -> false
}
})
if (isTy2ContainsTy1) {
// "E0308 cyclic type of infinite size"
TypeInferenceMarks.cyclicType.hit()
varUnificationTable.unifyVarValue(ty1r, TyUnknown)
} else {
varUnificationTable.unifyVarValue(ty1r, ty2)
}
}
}
return true
}
private fun combineIntOrFloatVar(ty1: TyInfer, ty2: Ty): Boolean {
when (ty1) {
is TyInfer.IntVar -> when (ty2) {
is TyInfer.IntVar -> intUnificationTable.unifyVarVar(ty1, ty2)
is TyInteger -> intUnificationTable.unifyVarValue(ty1, ty2)
else -> return false
}
is TyInfer.FloatVar -> when (ty2) {
is TyInfer.FloatVar -> floatUnificationTable.unifyVarVar(ty1, ty2)
is TyFloat -> floatUnificationTable.unifyVarValue(ty1, ty2)
else -> return false
}
is TyInfer.TyVar -> error("unreachable")
}
return true
}
private fun combineTypesNoVars(ty1: Ty, ty2: Ty): Boolean {
return ty1 === ty2 || when {
ty1 is TyPrimitive && ty2 is TyPrimitive && ty1 == ty2 -> true
ty1 is TyTypeParameter && ty2 is TyTypeParameter && ty1 == ty2 -> true
ty1 is TyReference && ty2 is TyReference && ty1.mutability == ty2.mutability -> {
combineTypes(ty1.referenced, ty2.referenced)
}
ty1 is TyPointer && ty2 is TyPointer && ty1.mutability == ty2.mutability -> {
combineTypes(ty1.referenced, ty2.referenced)
}
ty1 is TyArray && ty2 is TyArray &&
(ty1.size == null || ty2.size == null || ty1.size == ty2.size) -> combineTypes(ty1.base, ty2.base)
ty1 is TySlice && ty2 is TySlice -> combineTypes(ty1.elementType, ty2.elementType)
ty1 is TyTuple && ty2 is TyTuple -> combinePairs(ty1.types.zip(ty2.types))
ty1 is TyFunction && ty2 is TyFunction && ty1.paramTypes.size == ty2.paramTypes.size -> {
combinePairs(ty1.paramTypes.zip(ty2.paramTypes)) && combineTypes(ty1.retType, ty2.retType)
}
ty1 is TyAdt && ty2 is TyAdt && ty1.item == ty2.item -> {
combinePairs(ty1.typeArguments.zip(ty2.typeArguments))
}
ty1 is TyTraitObject && ty2 is TyTraitObject && ty1.trait == ty2.trait -> true
ty1 is TyAnon && ty2 is TyAnon && ty1.definition == ty2.definition -> true
ty1 is TyNever || ty2 is TyNever -> true
else -> false
}
}
fun combinePairs(pairs: List<Pair<Ty, Ty>>): Boolean {
var canUnify = true
for ((t1, t2) in pairs) {
canUnify = combineTypes(t1, t2) && canUnify
}
return canUnify
}
fun combineTraitRefs(ref1: TraitRef, ref2: TraitRef): Boolean =
ref1.trait.element == ref2.trait.element &&
combineTypes(ref1.selfTy, ref2.selfTy) &&
zipValues(ref1.trait.subst, ref2.trait.subst).all { (a, b) ->
combineTypes(a, b)
}
fun shallowResolve(ty: Ty): Ty {
if (ty !is TyInfer) return ty
return when (ty) {
is TyInfer.IntVar -> intUnificationTable.findValue(ty) ?: ty
is TyInfer.FloatVar -> floatUnificationTable.findValue(ty) ?: ty
is TyInfer.TyVar -> varUnificationTable.findValue(ty)?.let(this::shallowResolve) ?: ty
}
}
fun <T : TypeFoldable<T>> resolveTypeVarsIfPossible(ty: T): T {
return ty.foldTyInferWith(this::shallowResolve)
}
private fun fullyResolve(ty: Ty): Ty {
fun go(ty: Ty): Ty {
if (ty !is TyInfer) return ty
return when (ty) {
is TyInfer.IntVar -> intUnificationTable.findValue(ty) ?: TyInteger.DEFAULT
is TyInfer.FloatVar -> floatUnificationTable.findValue(ty) ?: TyFloat.DEFAULT
is TyInfer.TyVar -> varUnificationTable.findValue(ty)?.let(::go) ?: ty.origin ?: TyUnknown
}
}
return ty.foldTyInferWith(::go)
}
fun typeVarForParam(ty: TyTypeParameter): Ty {
return TyInfer.TyVar(ty)
}
/** Deeply normalize projection types. See [normalizeProjectionType] */
fun <T : TypeFoldable<T>> normalizeAssociatedTypesIn(ty: T, recursionDepth: Int = 0): TyWithObligations<T> {
val obligations = mutableListOf<Obligation>()
val normTy = ty.foldTyProjectionWith {
val normTy = normalizeProjectionType(it, recursionDepth)
obligations += normTy.obligations
normTy.value
}
return TyWithObligations(normTy, obligations)
}
/**
* Normalize a specific projection like `<T as Trait>::Item`.
* The result is always a type (and possibly additional obligations).
* If ambiguity arises, which implies that
* there are unresolved type variables in the projection, we will
* substitute a fresh type variable `$X` and generate a new
* obligation `<T as Trait>::Item == $X` for later.
*/
private fun normalizeProjectionType(projectionTy: TyProjection, recursionDepth: Int): TyWithObligations<Ty> {
return optNormalizeProjectionType(projectionTy, recursionDepth) ?: run {
val tyVar = TyInfer.TyVar(projectionTy)
val obligation = Obligation(recursionDepth + 1, Predicate.Projection(projectionTy, tyVar))
TyWithObligations(tyVar, listOf(obligation))
}
}
/**
* Normalize a specific projection like `<T as Trait>::Item`.
* The result is always a type (and possibly additional obligations).
* Returns `null` in the case of ambiguity, which indicates that there
* are unbound type variables.
*/
fun optNormalizeProjectionType(projectionTy: TyProjection, recursionDepth: Int): TyWithObligations<Ty>? =
optNormalizeProjectionTypeResolved(resolveTypeVarsIfPossible(projectionTy) as TyProjection, recursionDepth)
/** See [optNormalizeProjectionType] */
private fun optNormalizeProjectionTypeResolved(projectionTy: TyProjection, recursionDepth: Int): TyWithObligations<Ty>? {
if (projectionTy.type is TyInfer) return null
val cacheResult = projectionCache.tryStart(projectionTy)
return when (cacheResult) {
ProjectionCacheEntry.Ambiguous -> {
// If we found ambiguity the last time, that generally
// means we will continue to do so until some type in the
// key changes (and we know it hasn't, because we just
// fully resolved it).
// TODO rustc has an exception for closure types here
null
}
ProjectionCacheEntry.InProgress -> {
// While normalized A::B we are asked to normalize A::B.
// TODO rustc halts the compilation immediately (panics) here
TyWithObligations(TyUnknown)
}
ProjectionCacheEntry.Error -> {
// TODO report an error. See rustc's `normalize_to_error`
TyWithObligations(TyUnknown)
}
is ProjectionCacheEntry.NormalizedTy -> {
var ty = cacheResult.ty
// If we find the value in the cache, then return it along
// with the obligations that went along with it. Note
// that, when using a fulfillment context, these
// obligations could in principle be ignored: they have
// already been registered when the cache entry was
// created (and hence the new ones will quickly be
// discarded as duplicated). But when doing trait
// evaluation this is not the case.
// (See rustc's https://github.com/rust-lang/rust/issues/43132 )
if (!hasUnresolvedTypeVars(ty.value)) {
// Once we have inferred everything we need to know, we
// can ignore the `obligations` from that point on.
ty = TyWithObligations(ty.value)
projectionCache.putTy(projectionTy, ty)
}
ty
}
null -> {
val selResult = lookup.selectProjection(projectionTy, recursionDepth)
when (selResult) {
is SelectionResult.Ok -> {
val result = selResult.result ?: TyWithObligations(projectionTy)
projectionCache.putTy(projectionTy, pruneCacheValueObligations(result))
result
}
is SelectionResult.Err -> {
projectionCache.error(projectionTy)
// TODO report an error. See rustc's `normalize_to_error`
TyWithObligations(TyUnknown)
}
is SelectionResult.Ambiguous -> {
projectionCache.ambiguous(projectionTy)
null
}
}
}
}
}
/**
* If there are unresolved type variables, then we need to include
* any subobligations that bind them, at least until those type
* variables are fully resolved.
*/
private fun pruneCacheValueObligations(ty: TyWithObligations<Ty>): TyWithObligations<Ty> {
if (!hasUnresolvedTypeVars(ty.value)) return TyWithObligations(ty.value)
// I don't completely understand why we leave the only projection
// predicates here, but here is the comment from rustc about it
//
// If we found a `T: Foo<X = U>` predicate, let's check
// if `U` references any unresolved type
// variables. In principle, we only care if this
// projection can help resolve any of the type
// variables found in `result.value` -- but we just
// check for any type variables here, for fear of
// indirect obligations (e.g., we project to `?0`,
// but we have `T: Foo<X = ?1>` and `?1: Bar<X =
// ?0>`).
//
// We are only interested in `T: Foo<X = U>` predicates, where
// `U` references one of `unresolved_type_vars`.
val obligations = ty.obligations
.filter { it.predicate is Predicate.Projection && hasUnresolvedTypeVars(it.predicate) }
return TyWithObligations(ty.value, obligations)
}
private fun <T : TypeFoldable<T>> hasUnresolvedTypeVars(_ty: T): Boolean = _ty.visitWith(object : TypeVisitor {
override fun invoke(_ty: Ty): Boolean {
val ty = shallowResolve(_ty)
return when {
ty is TyInfer -> true
!ty.hasTyInfer -> false
else -> ty.superVisitWith(this)
}
}
})
fun instantiateBounds(
bounds: List<TraitRef>,
subst: Map<TyTypeParameter, Ty> = emptySubstitution,
recursionDepth: Int = 0
): Sequence<Obligation> {
return bounds.asSequence()
.map { it.substitute(subst) }
.map { normalizeAssociatedTypesIn(it, recursionDepth) }
.flatMap { it.obligations.asSequence() + Obligation(recursionDepth, Predicate.Trait(it.value)) }
}
/** Checks that [selfTy] satisfies all trait bounds of the [impl] */
fun canEvaluateBounds(impl: RsImplItem, selfTy: Ty): Boolean {
val ff = FulfillmentContext(this, lookup)
val subst = impl.generics.associate { it to typeVarForParam(it) }
return probe {
instantiateBounds(impl.bounds, subst).forEach(ff::registerPredicateObligation)
impl.typeReference?.type?.substitute(subst)?.let { combineTypes(selfTy, it) }
ff.selectUntilError()
}
}
override fun toString(): String {
return "RsInferenceContext(bindings=$bindings, exprTypes=$exprTypes)"
}
}
private class RsFnInferenceContext(
private val ctx: RsInferenceContext,
private val returnTy: Ty
) {
private val lookup get() = ctx.lookup
private val items get() = ctx.items
private val fulfill get() = ctx.fulfill
private val RsStructLiteralField.type: Ty get() = resolveToDeclaration?.typeReference?.type ?: TyUnknown
private fun resolveTypeVarsWithObligations(ty: Ty): Ty {
if (!ty.hasTyInfer) return ty
val tyRes = ctx.resolveTypeVarsIfPossible(ty)
if (!tyRes.hasTyInfer) return tyRes
selectObligationsWherePossible()
return ctx.resolveTypeVarsIfPossible(tyRes)
}
fun selectObligationsWherePossible() {
fulfill.selectWherePossible()
}
fun inferFnBody(block: RsBlock): Ty =
block.inferTypeCoercableTo(returnTy)
fun inferLambdaBody(expr: RsExpr): Ty =
if (expr is RsBlockExpr) {
// skipping diverging procession for lambda body
ctx.writeExprTy(expr, returnTy)
inferFnBody(expr.block)
} else {
expr.inferTypeCoercableTo(returnTy)
}
private fun RsBlock.inferTypeCoercableTo(expected: Ty): Ty =
inferType(expected, true)
private fun RsBlock.inferType(expected: Ty? = null, coerce: Boolean = false): Ty {
var isDiverging = false
for (stmt in stmtList) {
isDiverging = processStatement(stmt) || isDiverging
}
val type = (if (coerce) expr?.inferTypeCoercableTo(expected!!) else expr?.inferType(expected)) ?: TyUnit
return if (isDiverging) TyNever else type
}
// returns true if expr is always diverging
private fun processStatement(psi: RsStmt): Boolean = when (psi) {
is RsLetDecl -> {
val explicitTy = psi.typeReference?.type
?.let { normalizeAssociatedTypesIn(it) }
val inferredTy = explicitTy
?.let { psi.expr?.inferTypeCoercableTo(it) }
?: psi.expr?.inferType()
?: TyInfer.TyVar()
psi.pat?.extractBindings(explicitTy ?: resolveTypeVarsWithObligations(inferredTy))
inferredTy == TyNever
}
is RsExprStmt -> psi.expr.inferType() == TyNever
else -> false
}
private fun RsExpr.inferType(expected: Ty? = null): Ty {
if (ctx.isTypeInferred(this)) error("Trying to infer expression type twice")
val ty = when (this) {
is RsPathExpr -> inferPathExprType(this)
is RsStructLiteral -> inferStructLiteralType(this, expected)
is RsTupleExpr -> inferRsTupleExprType(this, expected)
is RsParenExpr -> this.expr.inferType(expected)
is RsUnitExpr -> TyUnit
is RsCastExpr -> inferCastExprType(this)
is RsCallExpr -> inferCallExprType(this, expected)
is RsDotExpr -> inferDotExprType(this, expected)
is RsLitExpr -> inferLitExprType(this, expected)
is RsBlockExpr -> this.block.inferType(expected)
is RsIfExpr -> inferIfExprType(this, expected)
is RsLoopExpr -> inferLoopExprType(this)
is RsWhileExpr -> inferWhileExprType(this)
is RsForExpr -> inferForExprType(this)
is RsMatchExpr -> inferMatchExprType(this, expected)
is RsUnaryExpr -> inferUnaryExprType(this, expected)
is RsBinaryExpr -> inferBinaryExprType(this)
is RsTryExpr -> inferTryExprType(this, expected)
is RsArrayExpr -> inferArrayType(this, expected)
is RsRangeExpr -> inferRangeType(this)
is RsIndexExpr -> inferIndexExprType(this)
is RsMacroExpr -> inferMacroExprType(this)
is RsLambdaExpr -> inferLambdaExprType(this, expected)
is RsRetExpr -> inferRetExprType(this)
is RsBreakExpr -> inferBreakExprType(this)
is RsContExpr -> TyNever
else -> TyUnknown
}
ctx.writeExprTy(this, ty)
return ty
}
private fun RsExpr.inferTypeCoercableTo(expected: Ty): Ty {
val inferred = inferType(expected)
coerce(this, inferred, expected)
return inferred
}
private fun coerce(expr: RsExpr, inferred: Ty, expected: Ty) {
coerceResolved(expr, resolveTypeVarsWithObligations(inferred), resolveTypeVarsWithObligations(expected))
}
private fun coerceResolved(expr: RsExpr, inferred: Ty, expected: Ty) {
val ok = tryCoerce(inferred, expected)
if (!ok) {
// ignoring possible false-positives (it's only basic experimental type checking)
val ignoredTys = listOf(
TyUnknown::class.java,
TyInfer.TyVar::class.java,
TyTypeParameter::class.java,
TyTraitObject::class.java
)
if (!expected.containsTyOfClass(ignoredTys) && !inferred.containsTyOfClass(ignoredTys)) {
// another awful hack: check that inner expressions did not annotated as an error
// to disallow annotation intersections. This should be done in a different way
fun PsiElement.isChildOf(psi: PsiElement) = this.ancestors.contains(psi)
if (ctx.diagnostics.all { !it.element.isChildOf(expr) }) {
ctx.reportTypeMismatch(expr, expected, inferred)
}
}
}
}
private fun tryCoerce(inferred: Ty, expected: Ty): Boolean {
return when {
// Coerce array to slice
inferred is TyReference && inferred.referenced is TyArray &&
expected is TyReference && expected.referenced is TySlice -> {
ctx.combineTypes(inferred.referenced.base, expected.referenced.elementType)
}
// Coerce reference to pointer
inferred is TyReference && expected is TyPointer &&
coerceMutability(inferred.mutability, expected.mutability) -> {
ctx.combineTypes(inferred.referenced, expected.referenced)
}
// Coerce mutable pointer to const pointer
inferred is TyPointer && inferred.mutability.isMut
&& expected is TyPointer && !expected.mutability.isMut -> {
ctx.combineTypes(inferred.referenced, expected.referenced)
}
// Coerce references
inferred is TyReference && expected is TyReference &&
coerceMutability(inferred.mutability, expected.mutability) -> {
coerceReference(inferred, expected)
}
// TODO trait object unsizing
else -> ctx.combineTypes(inferred, expected)
}
}
private fun coerceMutability(from: Mutability, to: Mutability): Boolean =
from == to || from.isMut && !to.isMut
/**
* Reborrows `&mut A` to `&mut B` and `&(mut) A` to `&B`.
* To match `A` with `B`, autoderef will be performed
*/
private fun coerceReference(inferred: TyReference, expected: TyReference): Boolean {
for (derefTy in lookup.coercionSequence(inferred).drop(1)) {
val derefTyRef = TyReference(derefTy, expected.mutability)
if (ctx.combineTypesIfOk(derefTyRef, expected)) return true
}
return false
}
fun inferLitExprType(expr: RsLitExpr, expected: Ty?): Ty {
val stubType = expr.stubType
return when (stubType) {
is RsStubLiteralType.Boolean -> TyBool
is RsStubLiteralType.Char -> if (stubType.isByte) TyInteger.U8 else TyChar
is RsStubLiteralType.String -> {
if (stubType.isByte) {
TyReference(TyArray(TyInteger.U8, stubType.length), IMMUTABLE)
} else {
TyReference(TyStr, IMMUTABLE)
}
}
is RsStubLiteralType.Integer -> {
val ty = stubType.kind
ty ?: when (expected) {
is TyInteger -> expected
TyChar -> TyInteger.U8
is TyPointer, is TyFunction -> TyInteger.USize
else -> TyInfer.IntVar()
}
}
is RsStubLiteralType.Float -> {
val ty = stubType.kind
ty ?: (expected?.takeIf { it is TyFloat } ?: TyInfer.FloatVar())
}
null -> TyUnknown
}
}
private fun inferPathExprType(expr: RsPathExpr): Ty {
val variants = resolvePath(expr.path, lookup).mapNotNull { it.downcast<RsNamedElement>() }
ctx.writePath(expr, variants)
val qualifier = expr.path.path
if (variants.size > 1 && qualifier != null) {
val resolved = collapseToTrait(variants.map { it.element })
if (resolved != null) {
// TODO remap subst
return instantiatePath(BoundElement(resolved, variants.first().subst), expr, tryRefinePath = true)
}
}
val first = variants.firstOrNull() ?: return TyUnknown
return instantiatePath(first, expr, tryRefinePath = variants.size == 1)
}
/** This works for `String::from` where multiple impls of `From` trait found for `String` */
private fun collapseToTrait(elements: List<RsNamedElement>): RsFunction? {
if (elements.size <= 1) return null
val traits = elements.mapNotNull {
val owner = (it as? RsFunction)?.owner
when (owner) {
is RsAbstractableOwner.Impl -> owner.impl.traitRef?.resolveToTrait
is RsAbstractableOwner.Trait -> owner.trait
else -> null
}
}
if (traits.size == elements.size && traits.toSet().size == 1) {
val fnName = elements.first().name
val trait = traits.first()
return trait.members?.functionList?.find { it.name == fnName } ?: return null
}
return null
}
private fun instantiatePath(
boundElement: BoundElement<RsNamedElement>,
pathExpr: RsPathExpr? = null,
tryRefinePath: Boolean = false
): Ty {
val (element, subst) = boundElement
val type = when (element) {
is RsPatBinding -> ctx.getBindingType(element)
is RsTypeDeclarationElement -> element.declaredType
is RsEnumVariant -> element.parentEnum.declaredType
is RsFunction -> element.typeOfValue
is RsConstant -> element.typeReference?.type ?: TyUnknown
is RsSelfParameter -> element.typeOfValue
else -> return TyUnknown
}
val typeParameters = when (element) {
is RsFunction -> {
val owner = element.owner
var (typeParameters, selfTy) = when (owner) {
is RsAbstractableOwner.Impl -> {
val typeParameters = instantiateBounds(owner.impl)
val selfTy = owner.impl.typeReference?.type?.substitute(typeParameters) ?: TyUnknown
subst[TyTypeParameter.self()]?.let { ctx.combineTypes(selfTy, it) }
typeParameters to selfTy
}
is RsAbstractableOwner.Trait -> {
val typeParameters = instantiateBounds(owner.trait)
// UFCS - add predicate `Self : Trait<Args>`
val selfTy = subst[TyTypeParameter.self()] ?: ctx.typeVarForParam(TyTypeParameter.self())
val boundTrait = BoundElement(owner.trait, owner.trait.generics.associateBy { it })
.substitute(typeParameters)
val traitRef = TraitRef(selfTy, boundTrait)
fulfill.registerPredicateObligation(Obligation(Predicate.Trait(traitRef)))
if (pathExpr != null && tryRefinePath) ctx.registerPathRefinement(pathExpr, traitRef)
typeParameters to selfTy
}
else -> emptySubstitution to null
}
typeParameters = instantiateBounds(element, selfTy, typeParameters)
typeParameters
}
is RsEnumVariant -> instantiateBounds(element.parentEnum)
is RsGenericDeclaration -> instantiateBounds(element)
else -> emptySubstitution
}
unifySubst(subst, typeParameters)
val tupleFields = (element as? RsFieldsOwner)?.tupleFields
return if (tupleFields != null) {
// Treat tuple constructor as a function
TyFunction(tupleFields.tupleFieldDeclList.map { it.typeReference.type }, type)
} else {
type
}.substitute(typeParameters).foldWith(this::normalizeAssociatedTypesIn)
}
private fun instantiateBounds(
element: RsGenericDeclaration,
selfTy: Ty? = null,
typeParameters: Substitution = emptySubstitution
): Substitution {
val map = run {
val map = typeParameters + element.generics.associate { it to ctx.typeVarForParam(it) }
if (selfTy != null) {
map + (TyTypeParameter.self() to selfTy)
} else {
map
}
}
ctx.instantiateBounds(element.bounds, map).forEach(fulfill::registerPredicateObligation)
return map
}
private fun <T : TypeFoldable<T>> normalizeAssociatedTypesIn(ty: T): T {
val (normTy, obligations) = ctx.normalizeAssociatedTypesIn(ty)
obligations.forEach(fulfill::registerPredicateObligation)
return normTy
}
private fun unifySubst(subst1: Substitution, subst2: Substitution) {
subst1.forEach { (k, v1) ->
subst2[k]?.let { v2 ->
if (k != v1 && k != TyTypeParameter.self() && v1 !is TyTypeParameter && v1 !is TyUnknown) {
ctx.combineTypes(v2, v1)
}
}
}
}
private fun inferStructLiteralType(expr: RsStructLiteral, expected: Ty?): Ty {
val boundElement = expr.path.reference.advancedResolve()
if (boundElement == null) {
for (field in expr.structLiteralBody.structLiteralFieldList) {
field.expr?.inferType()
}
// Handle struct update syntax { ..expression }
expr.structLiteralBody.expr?.inferType()
return TyUnknown
}
var (element, subst) = boundElement
// Resolve potential type aliases
while (element is RsTypeAlias) {
val resolved = (element.typeReference?.typeElement as? RsBaseType)?.path?.reference?.advancedResolve()
element = resolved?.element ?: return TyUnknown
subst = resolved.subst.substituteInValues(subst)
}
val genericDecl: RsGenericDeclaration = when (element) {
is RsStructItem -> element
is RsEnumVariant -> element.parentEnum
else -> return TyUnknown
}
val typeParameters = instantiateBounds(genericDecl)
unifySubst(subst, typeParameters)
if (expected != null) unifySubst(typeParameters, expected.typeParameterValues)
val type = when (element) {
is RsStructItem -> element.declaredType
is RsEnumVariant -> element.parentEnum.declaredType
else -> TyUnknown
}.substitute(typeParameters)
inferStructTypeArguments(expr, typeParameters)
// Handle struct update syntax { ..expression }
expr.structLiteralBody.expr?.inferTypeCoercableTo(type)
return type
}
private fun inferStructTypeArguments(literal: RsStructLiteral, typeParameters: Substitution) {
literal.structLiteralBody.structLiteralFieldList.mapNotNull { field ->
field.expr?.let { expr ->
val fieldType = field.type
expr.inferTypeCoercableTo(fieldType.substitute(typeParameters))
}
}
}
private fun inferRsTupleExprType(expr: RsTupleExpr, expected: Ty?): Ty {
return TyTuple(inferExprList(expr.exprList, (expected as? TyTuple)?.types))
}
private fun inferExprList(exprs: List<RsExpr>, expected: List<Ty>?): List<Ty> {
val extended = expected.orEmpty().asSequence().infiniteWithTyUnknown()
return exprs.asSequence().zip(extended).map { (expr, ty) -> expr.inferTypeCoercableTo(ty) }.toList()
}
private fun inferCastExprType(expr: RsCastExpr): Ty {
expr.expr.inferType()
return expr.typeReference.type
}
private fun inferCallExprType(expr: RsCallExpr, expected: Ty?): Ty {
val ty = resolveTypeVarsWithObligations(expr.expr.inferType()) // or error
val argExprs = expr.valueArgumentList.exprList
// `struct S; S();`
if (ty is TyAdt && argExprs.isEmpty()) return ty
val calleeType = lookup.asTyFunction(ty)?.register() ?: unknownTyFunction(argExprs.size)
if (expected != null) ctx.combineTypes(expected, calleeType.retType)
inferArgumentTypes(calleeType.paramTypes, argExprs)
return calleeType.retType
}
private fun inferMethodCallExprType(receiver: Ty, methodCall: RsMethodCall, expected: Ty?): Ty {
val argExprs = methodCall.valueArgumentList.exprList
val callee = run {
val variants = resolveMethodCallReferenceWithReceiverType(lookup, receiver, methodCall)
val callee = pickSingleMethod(variants, methodCall)
// If we failed to resolve ambiguity just write the all possible methods
val variantsForDisplay = (callee?.let(::listOf) ?: variants).map { it.element }
ctx.writeResolvedMethod(methodCall, variantsForDisplay)
callee ?: variants.firstOrNull()
}
if (callee == null) {
val methodType = unknownTyFunction(argExprs.size)
inferArgumentTypes(methodType.paramTypes, argExprs)
return methodType.retType
}
val impl = callee.impl
var typeParameters = if (impl != null) {
val typeParameters = instantiateBounds(impl)
impl.typeReference?.type?.substitute(typeParameters)?.let { ctx.combineTypes(callee.selfTy, it) }
if (callee.element.owner is RsAbstractableOwner.Trait) {
impl.traitRef?.resolveToBoundTrait?.substitute(typeParameters)?.subst ?: emptySubstitution
} else {
typeParameters
}
} else {
// Method has been resolved to a trait, so we should add a predicate
// `Self : Trait<Args>` to select args and also refine method path if possible.
// Method path refinement needed if there are multiple impls of the same trait to the same type
val trait = (callee.element.owner as RsAbstractableOwner.Trait).trait
when (callee.selfTy) {
// All these branches except `else` are optimization, they can be removed without loss of functionality
is TyTypeParameter -> callee.selfTy.getTraitBoundsTransitively()
.find { it.element == trait }?.subst ?: emptySubstitution
is TyAnon -> callee.selfTy.getTraitBoundsTransitively()
.find { it.element == trait }?.subst ?: emptySubstitution
is TyTraitObject -> callee.selfTy.trait.flattenHierarchy
.find { it.element == trait }?.subst ?: emptySubstitution
else -> {
val typeParameters = instantiateBounds(trait)
val boundTrait = BoundElement(trait, trait.generics.associateBy { it })
.substitute(typeParameters)
val traitRef = TraitRef(callee.selfTy, boundTrait)
fulfill.registerPredicateObligation(Obligation(Predicate.Trait(traitRef)))
ctx.registerMethodRefinement(methodCall, traitRef)
typeParameters
}
}
}
typeParameters = instantiateBounds(callee.element, callee.selfTy, typeParameters)
val fnSubst = run {
val typeArguments = methodCall.typeArgumentList?.typeReferenceList.orEmpty().map { it.type }
if (typeArguments.isEmpty()) {
emptySubstitution