-
Notifications
You must be signed in to change notification settings - Fork 380
/
TypeInferenceWalker.kt
1388 lines (1213 loc) · 56.8 KB
/
TypeInferenceWalker.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.progress.ProgressManager
import com.intellij.psi.PsiElement
import com.intellij.util.containers.isNullOrEmpty
import org.rust.lang.core.macros.MacroExpansion
import org.rust.lang.core.macros.expandedFromSequence
import org.rust.lang.core.psi.*
import org.rust.lang.core.psi.ext.*
import org.rust.lang.core.resolve.*
import org.rust.lang.core.resolve.ref.*
import org.rust.lang.core.stubs.RsStubLiteralKind
import org.rust.lang.core.types.*
import org.rust.lang.core.types.ty.*
import org.rust.lang.utils.RsDiagnostic
import org.rust.lang.utils.evaluation.ExprValue
import org.rust.lang.utils.evaluation.RsConstExprEvaluator
import org.rust.openapiext.forEachChild
import org.rust.stdext.notEmptyOrLet
import org.rust.stdext.singleOrFilter
import org.rust.stdext.singleOrLet
class RsTypeInferenceWalker(
private val ctx: RsInferenceContext,
private val returnTy: Ty
) {
private var tryTy: Ty? = returnTy
private var yieldTy: Ty? = null
private var macroExprDepth: Int = 0
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)
}
private fun selectObligationsWherePossible() {
fulfill.selectWherePossible()
}
private fun inferBlockExprType(blockExpr: RsBlockExpr, expected: Ty? = null): Ty =
when {
blockExpr.isTry -> inferTryBlockExprType(blockExpr, expected)
blockExpr.isAsync -> inferAsyncBlockExprType(blockExpr)
else -> {
val type = blockExpr.block.inferType(expected)
inferLabeledExprType(blockExpr, type, true)
}
}
private fun inferTryBlockExprType(blockExpr: RsBlockExpr, expected: Ty? = null): Ty {
require(blockExpr.isTry)
val oldTryTy = tryTy
try {
tryTy = expected ?: TyInfer.TyVar()
val resultTy = tryTy ?: TyUnknown
val okTy = blockExpr.block.inferType()
registerTryProjection(resultTy, "Ok", okTy)
return resultTy
} finally {
tryTy = oldTryTy
}
}
private fun inferAsyncBlockExprType(blockExpr: RsBlockExpr): Ty {
require(blockExpr.isAsync)
val outputTy = blockExpr.block.inferType()
return items.makeFuture(outputTy)
}
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
val expandedStmts = expandedStmts
val tailExpr = expandedStmts.lastOrNull()
?.let { it as? RsExpr }
?.takeIf { e ->
// If tail expr is expanded from a macro, we should check that this macro doesn't have
// semicolon (`foo!();`), otherwice it's not a tail expr but a regular statement
e.expandedFromSequence.all {
val bracesKind = it.bracesKind ?: return@all false
!bracesKind.needsSemicolon || it.semicolon == null
}
}
for (stmt in expandedStmts) {
val result = when (stmt) {
tailExpr -> false
is RsStmt -> processStatement(stmt)
is RsExpr -> stmt.inferType() == TyNever
else -> false
}
isDiverging = result || isDiverging
}
val type = (if (coerce) tailExpr?.inferTypeCoercableTo(expected!!) else tailExpr?.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 expr = psi.expr
// We need to know type before coercion to correctly identify if expr is always diverging
// so we can't call `inferTypeCoercableTo` directly here
val (inferredTy, coercedInferredTy) = if (expr != null) {
val inferredTy = expr.inferType(explicitTy)
val coercedTy = if (explicitTy != null && coerce(expr, inferredTy, explicitTy)) {
explicitTy
} else {
inferredTy
}
inferredTy to coercedTy
} else {
TyUnknown to TyInfer.TyVar()
}
psi.pat?.extractBindings(explicitTy ?: resolveTypeVarsWithObligations(coercedInferredTy))
inferredTy == TyNever
}
is RsExprStmt -> psi.expr.inferType() == TyNever
else -> false
}
private fun RsExpr.inferType(expected: Ty? = null): Ty {
ProgressManager.checkCanceled()
if (ctx.isTypeInferred(this)) error("Trying to infer expression type twice")
if (expected != null) {
when (this) {
is RsPathExpr -> ctx.writeExpectedPathExprTy(this, expected)
is RsDotExpr -> ctx.writeExpectedDotExprTy(this, expected)
}
}
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 -> inferBlockExprType(this, 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)
is RsArrayExpr -> inferArrayType(this, expected)
is RsRangeExpr -> inferRangeType(this)
is RsIndexExpr -> inferIndexExprType(this)
is RsMacroExpr -> inferMacroExprType(this, expected)
is RsLambdaExpr -> inferLambdaExprType(this, expected)
is RsYieldExpr -> inferYieldExprType(this)
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)
return if (coerce(this, inferred, expected)) expected else inferred
}
@JvmName("inferTypeCoercableTo_")
fun inferTypeCoercableTo(expr: RsExpr, expected: Ty): Ty =
expr.inferTypeCoercableTo(expected)
private fun coerce(element: RsElement, inferred: Ty, expected: Ty): Boolean {
return coerceResolved(element, resolveTypeVarsWithObligations(inferred), resolveTypeVarsWithObligations(expected))
}
private fun coerceResolved(element: RsElement, inferred: Ty, expected: Ty): Boolean {
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,
TyProjection::class.java,
TyTraitObject::class.java,
TyAnon::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
if (ctx.diagnostics.all { !element.isAncestorOf(it.element) }) {
ctx.reportTypeMismatch(element, expected, inferred)
}
}
}
return ok
}
private fun tryCoerce(inferred: Ty, expected: Ty): Boolean {
return when {
inferred == TyNever -> true
// 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)) {
// TODO proper handling of lifetimes
val derefTyRef = TyReference(derefTy, expected.mutability, expected.region)
if (ctx.combineTypesIfOk(derefTyRef, expected)) return true
}
return false
}
private fun inferLitExprType(expr: RsLitExpr, expected: Ty?): Ty {
return when (val stubKind = expr.stubKind) {
is RsStubLiteralKind.Boolean -> TyBool
is RsStubLiteralKind.Char -> if (stubKind.isByte) TyInteger.U8 else TyChar
is RsStubLiteralKind.String -> {
// TODO infer the actual lifetime
if (stubKind.isByte) {
TyReference(TyArray(TyInteger.U8, stubKind.value?.length?.toLong() ?: 0), Mutability.IMMUTABLE)
} else {
TyReference(TyStr, Mutability.IMMUTABLE)
}
}
is RsStubLiteralKind.Integer -> {
val ty = stubKind.ty
ty ?: when (expected) {
is TyInteger -> expected
TyChar -> TyInteger.U8
is TyPointer, is TyFunction -> TyInteger.USize
else -> TyInfer.IntVar()
}
}
is RsStubLiteralKind.Float -> {
val ty = stubKind.ty
ty ?: (expected?.takeIf { it is TyFloat } ?: TyInfer.FloatVar())
}
null -> TyUnknown
}
}
private fun inferPathExprType(expr: RsPathExpr): Ty {
val path = expr.path
val resolveVariants = resolvePathRaw(path, lookup)
val assocVariants = resolveVariants.filterIsInstance<AssocItemScopeEntry>()
val filteredVariants = if (resolveVariants.size == assocVariants.size) {
val variants = filterAssocItems(assocVariants, expr)
val fnVariants = variants.mapNotNull { it.element as? RsFunction }
if (variants.size > 1 && fnVariants.size == variants.size && path.path != null) {
val resolved = collapseToTrait(fnVariants)
if (resolved != null) {
ctx.writePath(expr, variants.map { ResolvedPath.from(it) })
val subst = collapseSubst(
resolved,
variants.mapNotNull { e ->
(e.element as? RsGenericDeclaration)?.let { BoundElement(it, e.subst) }
}
)
val scopeEntry = variants.first().copy(
element = resolved,
subst = subst,
source = TraitImplSource.Collapsed((resolved.owner as RsAbstractableOwner.Trait).trait)
)
return instantiatePath(resolved, scopeEntry, expr)
}
}
variants
} else {
resolveVariants
}
ctx.writePath(expr, filteredVariants.mapNotNull { ResolvedPath.from(it) })
val first = filteredVariants.singleOrNull() ?: return TyUnknown
return instantiatePath(first.element ?: return TyUnknown, first, expr)
}
/** This works for `String::from` where multiple impls of `From` trait found for `String` */
private fun collapseToTrait(elements: List<RsFunction>): RsFunction? {
if (elements.size <= 1) return null
val traits = elements.mapNotNull {
when (val owner = it.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()
val functionList = trait.members?.functionList ?: return null
return functionList.singleOrNull { it.name == fnName }
}
return null
}
/** See test `test type arguments remap on collapse to trait` */
private fun collapseSubst(parentFn: RsFunction, variants: List<BoundElement<RsGenericDeclaration>>): Substitution {
//TODO remap lifetimes
val collapsed = mutableMapOf<TyTypeParameter, Ty>()
val generics = parentFn.generics
for (fn in variants) {
for ((key, newValue) in generics.zip(fn.positionalTypeArguments)) {
@Suppress("NAME_SHADOWING")
collapsed.compute(key) { key, oldValue ->
if (oldValue == null || oldValue == newValue) newValue else TyInfer.TyVar(key)
}
}
}
variants.first().subst[TyTypeParameter.self()]?.let { collapsed[TyTypeParameter.self()] = it }
return collapsed.toTypeSubst()
}
private fun instantiatePath(
element: RsElement,
scopeEntry: ScopeEntry,
pathExpr: RsPathExpr
): Ty {
val subst = instantiatePathGenerics(pathExpr.path, BoundElement(element, scopeEntry.subst)).subst
val type = when (element) {
is RsPatBinding -> ctx.getBindingType(element)
is RsTypeDeclarationElement -> element.declaredType
is RsEnumVariant -> element.parentEnum.declaredType
is RsFunction -> element.type
is RsConstant -> element.typeReference?.type ?: TyUnknown
is RsConstParameter -> element.typeReference?.type ?: TyUnknown
is RsSelfParameter -> element.typeOfValue
else -> return TyUnknown
}
val typeParameters = when {
scopeEntry is AssocItemScopeEntry && element is RsAbstractable -> {
val owner = element.owner
val (typeParameters, selfTy) = when (owner) {
is RsAbstractableOwner.Impl -> {
val typeParameters = ctx.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 = ctx.instantiateBounds(owner.trait)
// UFCS - add predicate `Self : Trait<Args>`
val selfTy = subst[TyTypeParameter.self()] ?: ctx.typeVarForParam(TyTypeParameter.self())
val newSubst = owner.trait.generics.associateBy { it }.toTypeSubst()
val boundTrait = BoundElement(owner.trait, newSubst)
.substitute(typeParameters)
val traitRef = TraitRef(selfTy, boundTrait)
fulfill.registerPredicateObligation(Obligation(Predicate.Trait(traitRef)))
when (scopeEntry.source) {
is TraitImplSource.Object, is TraitImplSource.Collapsed -> {
ctx.registerPathRefinement(pathExpr, traitRef)
}
}
typeParameters to selfTy
}
else -> emptySubstitution to null
}
if (element is RsGenericDeclaration) {
ctx.instantiateBounds(element, selfTy, typeParameters)
} else {
typeParameters
}
}
element is RsEnumVariant -> ctx.instantiateBounds(element.parentEnum)
element is RsGenericDeclaration -> ctx.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(associatedTypeNormalizer)
}
private fun <T : TypeFoldable<T>> normalizeAssociatedTypesIn(ty: T): T {
val (normTy, obligations) = ctx.normalizeAssociatedTypesIn(ty)
obligations.forEach(fulfill::registerPredicateObligation)
return normTy
}
private inner class AssociatedTypeNormalizer : TypeFolder {
override fun foldTy(ty: Ty): Ty = normalizeAssociatedTypesIn(ty)
}
private val associatedTypeNormalizer = AssociatedTypeNormalizer()
private fun unifySubst(subst1: Substitution, subst2: Substitution) {
subst1.typeSubst.forEach { (k, v1) ->
subst2[k]?.let { v2 ->
if (k != v1 && k != TyTypeParameter.self() && v1 !is TyTypeParameter && v1 !is TyUnknown) {
ctx.combineTypes(v2, v1)
}
}
}
// TODO take into account the lifetimes
}
private fun inferStructLiteralType(expr: RsStructLiteral, expected: Ty?): Ty {
val boundElement = expr.path.reference.advancedDeepResolve()
if (boundElement == null) {
for (field in expr.structLiteralBody.structLiteralFieldList) {
field.expr?.inferType()
}
// Handle struct update syntax { ..expression }
expr.structLiteralBody.expr?.inferType()
return TyUnknown
}
val (element, subst) = boundElement
val genericDecl: RsGenericDeclaration? = when (element) {
is RsStructItem -> element
is RsEnumVariant -> element.parentEnum
else -> null
}
val typeParameters = genericDecl?.let { ctx.instantiateBounds(it) } ?: emptySubstitution
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.filterNotNull().forEach { field ->
val fieldTy = field.type.substitute(typeParameters)
val expr = field.expr
if (expr != null) {
expr.inferTypeCoercableTo(fieldTy)
} else {
val bindingTy = field.resolveToBinding()?.let { ctx.getBindingType(it) } ?: TyUnknown
coerce(field, bindingTy, fieldTy)
}
}
}
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 callee = expr.expr
val ty = resolveTypeVarsWithObligations(callee.inferType()) // or error
// `struct S; S();`
if (callee is RsPathExpr) {
ctx.getResolvedPath(callee).singleOrNull()?.element?.let {
if (it is RsFieldsOwner && it.isFieldless) {
return ty
}
}
}
val argExprs = expr.valueArgumentList.exprList
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(receiver, variants, methodCall)
// If we failed to resolve ambiguity just write the all possible methods
val variantsForDisplay = (callee?.let(::listOf) ?: variants)
ctx.writeResolvedMethod(methodCall, variantsForDisplay)
callee ?: variants.firstOrNull()
}
if (callee == null) {
val methodType = unknownTyFunction(argExprs.size)
inferArgumentTypes(methodType.paramTypes, argExprs)
return methodType.retType
}
var typeParameters = ctx.instantiateMethodOwnerSubstitution(callee, methodCall)
// TODO: borrow adjustments for self parameter
/*
if (callee.selfTy is TyReference) {
val adjustment = BorrowReference( callee.selfTy)
ctx.addAdjustment(methodCall.receiver, adjustment)
}
*/
typeParameters = ctx.instantiateBounds(callee.element, callee.selfTy, typeParameters)
val fnSubst = run {
val typeArguments = methodCall.typeArgumentList?.typeReferenceList.orEmpty().map { it.type }
if (typeArguments.isEmpty()) {
emptySubstitution
} else {
val parameters = callee.element.typeParameterList?.typeParameterList.orEmpty()
.map { TyTypeParameter.named(it) }
parameters.zip(typeArguments).toMap().toTypeSubst()
}
}
unifySubst(fnSubst, typeParameters)
val methodType = (callee.element.type)
.substitute(typeParameters)
.foldWith(associatedTypeNormalizer) as TyFunction
if (expected != null && !callee.element.isAsync) ctx.combineTypes(expected, methodType.retType)
// drop first element of paramTypes because it's `self` param
// and it doesn't have value in `methodCall.valueArgumentList.exprList`
inferArgumentTypes(methodType.paramTypes.drop(1), argExprs)
return methodType.retType
}
private fun <T: AssocItemScopeEntryBase<E>, E> filterAssocItems(variants: List<T>, context: RsElement): List<T> {
return variants.singleOrLet { list ->
// 1. filter traits that are not imported
TypeInferenceMarks.methodPickTraitScope.hit()
val traitToCallee = hashMapOf<RsTraitItem, MutableList<T>>()
val filtered = mutableListOf<T>()
for (callee in list) {
val trait = callee.source.impl?.traitRef?.resolveToTrait()
if (trait != null) {
traitToCallee.getOrPut(trait) { mutableListOf() }.add(callee)
} else {
filtered.add(callee) // inherent impl
}
}
traitToCallee.keys.filterInScope(context).forEach {
filtered += traitToCallee.getValue(it)
}
if (filtered.isNotEmpty()) {
filtered
} else {
TypeInferenceMarks.methodPickTraitsOutOfScope.hit()
list
}
}.singleOrFilter { callee ->
// 2. Filter methods by trait bounds (try to select all obligations for each impl)
TypeInferenceMarks.methodPickCheckBounds.hit()
val impl = callee.source.impl ?: return@singleOrFilter true
ctx.canEvaluateBounds(impl, callee.selfTy)
}
}
private fun pickSingleMethod(receiver: Ty, variants: List<MethodResolveVariant>, methodCall: RsMethodCall): MethodResolveVariant? {
val filtered = filterAssocItems(variants, methodCall).singleOrLet { list ->
// 3. Pick results matching receiver type
TypeInferenceMarks.methodPickDerefOrder.hit()
fun pick(ty: Ty): List<MethodResolveVariant> =
list.filter { it.element.selfParameter?.typeOfValue(it.selfTy) == ty }
// https://github.com/rust-lang/rust/blob/a646c912/src/librustc_typeck/check/method/probe.rs#L885
lookup.coercionSequence(receiver).mapNotNull { ty ->
pick(ty)
// TODO do something with lifetimes
.notEmptyOrLet { pick(TyReference(ty, Mutability.IMMUTABLE)) }
.notEmptyOrLet { pick(TyReference(ty, Mutability.MUTABLE)) }
.takeIf { it.isNotEmpty() }
}.firstOrNull() ?: emptyList()
}
return when (filtered.size) {
0 -> null
1 -> filtered.single()
else -> {
// 4. Try to collapse multiple resolved methods of the same trait, e.g.
// ```rust
// trait Foo<T> { fn foo(&self, _: T) {} }
// impl Foo<Bar> for S { fn foo(&self, _: Bar) {} }
// impl Foo<Baz> for S { fn foo(&self, _: Baz) {} }
// ```
// In this case we `filtered` list contains 2 function defined in 2 impls.
// We want to collapse them to the single function defined in the trait.
// Specific impl will be selected later according to the method parameter type.
val first = filtered.first()
collapseToTrait(filtered.map { it.element })?.let { fn ->
TypeInferenceMarks.methodPickCollapseTraits.hit()
MethodResolveVariant(
first.name,
fn,
first.selfTy,
first.derefCount,
TraitImplSource.Collapsed((fn.owner as RsAbstractableOwner.Trait).trait)
)
}
}
}
}
private fun unknownTyFunction(arity: Int): TyFunction =
TyFunction(generateSequence { TyUnknown }.take(arity).toList(), TyUnknown)
private fun inferArgumentTypes(argDefs: List<Ty>, argExprs: List<RsExpr>) {
// We do this just like rustc, and comments copied from rustc too
// We do this in a pretty awful way: first we typecheck any arguments
// that are not closures, then we typecheck the closures. This is so
// that we have more information about the types of arguments when we
// typecheck the functions.
for (checkLambdas in booleanArrayOf(false, true)) {
// More awful hacks: before we check argument types, try to do
// an "opportunistic" vtable resolution of any trait bounds on
// the call. This helps coercions.
if (checkLambdas) {
selectObligationsWherePossible()
}
val argDefsExt = argDefs.asSequence()
.map(ctx::resolveTypeVarsIfPossible)
// extending argument definitions to be sure that type inference launched for each arg expr
.infiniteWithTyUnknown()
for ((type, expr) in argDefsExt.zip(argExprs.asSequence().map(::unwrapParenExprs))) {
val isLambda = expr is RsLambdaExpr
if (isLambda != checkLambdas) continue
expr.inferTypeCoercableTo(type)
}
}
}
private fun inferFieldExprType(receiver: Ty, fieldLookup: RsFieldLookup): Ty {
if (fieldLookup.identifier?.text == "await" && fieldLookup.isEdition2018) {
return receiver.lookupFutureOutputTy(lookup)
}
val variants = resolveFieldLookupReferenceWithReceiverType(lookup, receiver, fieldLookup)
ctx.writeResolvedField(fieldLookup, variants.map { it.element })
val field = variants.firstOrNull()
if (field == null) {
for ((index, type) in lookup.coercionSequence(receiver).withIndex()) {
if (type is TyTuple) {
ctx.addAdjustment(fieldLookup.parentDotExpr.expr, Adjustment.Deref(receiver), index)
val fieldIndex = fieldLookup.integerLiteral?.text?.toIntOrNull() ?: return TyUnknown
return type.types.getOrElse(fieldIndex) { TyUnknown }
}
}
return TyUnknown
}
ctx.addAdjustment(fieldLookup.parentDotExpr.expr, Adjustment.Deref(receiver), field.derefCount)
val fieldElement = field.element
val raw = (fieldElement as? RsFieldDecl)?.typeReference?.type ?: TyUnknown
return raw.substitute(field.selfTy.typeParameterValues).foldWith(associatedTypeNormalizer)
}
private fun inferDotExprType(expr: RsDotExpr, expected: Ty?): Ty {
val receiver = resolveTypeVarsWithObligations(expr.expr.inferType())
val methodCall = expr.methodCall
val fieldLookup = expr.fieldLookup
return when {
methodCall != null -> inferMethodCallExprType(receiver, methodCall, expected)
fieldLookup != null -> inferFieldExprType(receiver, fieldLookup)
else -> TyUnknown
}
}
private fun inferLoopExprType(expr: RsLoopExpr): Ty {
expr.block?.inferType()
return inferLabeledExprType(expr, TyNever, false)
}
private fun inferLabeledExprType(expr: RsLabeledExpression, baseType: Ty, matchOnlyByLabel: Boolean): Ty {
val returningTypes = mutableListOf(baseType)
val label = expr.labelDecl?.name
fun collectReturningTypes(element: PsiElement, matchOnlyByLabel: Boolean) {
element.forEachChild { child ->
when (child) {
is RsBreakExpr -> {
collectReturningTypes(child, matchOnlyByLabel)
if (!matchOnlyByLabel && child.label == null || child.label?.referenceName == label) {
returningTypes += child.expr?.let(ctx::getExprType) ?: TyUnit
}
}
is RsLabeledExpression -> {
if (label != null) {
collectReturningTypes(child, true)
}
}
else -> collectReturningTypes(child, matchOnlyByLabel)
}
}
}
if (label != null || !matchOnlyByLabel) {
collectReturningTypes(expr, matchOnlyByLabel)
}
return getMoreCompleteType(returningTypes)
}
private fun inferForExprType(expr: RsForExpr): Ty {
val exprTy = resolveTypeVarsWithObligations(expr.expr?.inferType() ?: TyUnknown)
val itemTy = resolveTypeVarsWithObligations(lookup.findIteratorItemType(exprTy)?.register() ?: TyUnknown)
expr.pat?.extractBindings(itemTy)
expr.block?.inferType()
return TyUnit
}
private fun inferWhileExprType(expr: RsWhileExpr): Ty {
expr.condition?.inferTypes()
expr.block?.inferType()
return TyUnit
}
private fun inferMatchExprType(expr: RsMatchExpr, expected: Ty?): Ty {
val matchingExprTy = resolveTypeVarsWithObligations(expr.expr?.inferType() ?: TyUnknown)
val arms = expr.arms
for (arm in arms) {
arm.orPats.extractBindings(matchingExprTy)
arm.expr?.inferType(expected)
arm.matchArmGuard?.expr?.inferType(TyBool)
}
return getMoreCompleteType(arms.mapNotNull { it.expr?.let(ctx::getExprType) })
}
private fun inferUnaryExprType(expr: RsUnaryExpr, expected: Ty?): Ty {
val innerExpr = expr.expr ?: return TyUnknown
return when (expr.operatorType) {
UnaryOperator.REF -> inferRefType(innerExpr, expected, Mutability.IMMUTABLE)
UnaryOperator.REF_MUT -> inferRefType(innerExpr, expected, Mutability.MUTABLE)
UnaryOperator.DEREF -> {
// expectation must NOT be used for deref
val base = resolveTypeVarsWithObligations(innerExpr.inferType())
val deref = lookup.deref(base)
if (deref == null && base != TyUnknown) {
ctx.addDiagnostic(RsDiagnostic.DerefError(expr, base))
}
deref ?: TyUnknown
}
UnaryOperator.MINUS -> innerExpr.inferType(expected)
UnaryOperator.NOT -> innerExpr.inferType(expected)
UnaryOperator.BOX -> {
val expectedInner = (expected as? TyAdt)?.takeIf { it.item == items.Box }?.typeArguments?.getOrNull(0)
items.makeBox(innerExpr.inferType(expectedInner))
}
}
}
private fun inferRefType(expr: RsExpr, expected: Ty?, mutable: Mutability): Ty =
TyReference(expr.inferType((expected as? TyReference)?.referenced), mutable) // TODO infer the actual lifetime
private fun inferIfExprType(expr: RsIfExpr, expected: Ty?): Ty {
expr.condition?.inferTypes()
val blockTys = mutableListOf<Ty?>()
blockTys.add(expr.block?.inferType(expected))
val elseBranch = expr.elseBranch
if (elseBranch != null) {
blockTys.add(elseBranch.ifExpr?.inferType(expected))
blockTys.add(elseBranch.block?.inferType(expected))
}
return if (expr.elseBranch == null) TyUnit else getMoreCompleteType(blockTys.filterNotNull())
}
private fun RsCondition.inferTypes() {
val orPats = orPats
if (orPats != null) {
// if let Some(a) = ... {}
// if let V1(a) | V2(a) = ... {}
// or
// while let Some(a) = ... {}
// while let V1(a) | V2(a) = ... {}
val exprTy = resolveTypeVarsWithObligations(expr.inferType())
orPats.extractBindings(exprTy)
} else {
expr.inferType(TyBool)
}
}
private fun inferBinaryExprType(expr: RsBinaryExpr): Ty {
val lhsType = resolveTypeVarsWithObligations(expr.left.inferType())
val op = expr.operatorType
val (rhsType, retTy) = when (op) {
is BoolOp -> {
if (op is OverloadableBinaryOperator) {
val rhsTypeVar = TyInfer.TyVar()
enforceOverloadedBinopTypes(lhsType, rhsTypeVar, op)
val rhsType = resolveTypeVarsWithObligations(expr.right?.inferTypeCoercableTo(rhsTypeVar)
?: TyUnknown)
val lhsAdjustment = Adjustment.BorrowReference(TyReference(lhsType, Mutability.IMMUTABLE))
ctx.addAdjustment(expr.left, lhsAdjustment)
val rhsAdjustment = Adjustment.BorrowReference(TyReference(rhsType, Mutability.IMMUTABLE))
expr.right?.let { ctx.addAdjustment(it, rhsAdjustment) }
rhsType to TyBool
} else {
val rhsType = resolveTypeVarsWithObligations(expr.right?.inferTypeCoercableTo(lhsType) ?: TyUnknown)
rhsType to TyBool
}
}
is ArithmeticOp -> {
val rhsTypeVar = TyInfer.TyVar()
val retTy = lookup.findArithmeticBinaryExprOutputType(lhsType, rhsTypeVar, op)?.register() ?: TyUnknown
val rhsType = resolveTypeVarsWithObligations(expr.right?.inferTypeCoercableTo(rhsTypeVar) ?: TyUnknown)
rhsType to retTy
}
is ArithmeticAssignmentOp -> {
val rhsTypeVar = TyInfer.TyVar()
enforceOverloadedBinopTypes(lhsType, rhsTypeVar, op)
val rhsType = resolveTypeVarsWithObligations(expr.right?.inferTypeCoercableTo(rhsTypeVar) ?: TyUnknown)
val lhsAdjustment = Adjustment.BorrowReference(TyReference(lhsType, Mutability.MUTABLE))
ctx.addAdjustment(expr.left, lhsAdjustment)
rhsType to TyUnit
}
AssignmentOp.EQ -> {
val rhsType = expr.right?.inferTypeCoercableTo(lhsType) ?: TyUnknown
rhsType to TyUnit
}
}
if (op != AssignmentOp.EQ && isBuiltinBinop(lhsType, rhsType, op)) {
val builtinRetTy = enforceBuiltinBinopTypes(lhsType, rhsType, op)
if (op !is ArithmeticAssignmentOp) {
ctx.combineTypes(builtinRetTy, retTy)
}
}
return retTy
}
private fun enforceOverloadedBinopTypes(lhsType: Ty, rhsType: Ty, op: OverloadableBinaryOperator) {
selectOverloadedOp(lhsType, rhsType, op)?.let { fulfill.registerPredicateObligation(it) }
}
private fun selectOverloadedOp(lhsType: Ty, rhsType: Ty, op: OverloadableBinaryOperator): Obligation? {
val trait = op.findTrait(items) ?: return null
return Obligation(Predicate.Trait(TraitRef(lhsType, trait.withSubst(rhsType))))
}
private fun isBuiltinBinop(lhsType: Ty, rhsType: Ty, op: BinaryOperator): Boolean = when (op.category) {
BinOpCategory.Shortcircuit -> true
BinOpCategory.Shift -> lhsType.isIntegral && rhsType.isIntegral
BinOpCategory.Math -> lhsType.isIntegral && rhsType.isIntegral ||
lhsType.isFloat && rhsType.isFloat
BinOpCategory.Bitwise -> lhsType.isIntegral && rhsType.isIntegral ||
lhsType.isFloat && rhsType.isFloat ||
lhsType == TyBool && rhsType == TyBool
BinOpCategory.Comparison -> lhsType.isScalar && rhsType.isScalar
}
private fun enforceBuiltinBinopTypes(lhsType: Ty, rhsType: Ty, op: BinaryOperator): Ty = when (op.category) {
BinOpCategory.Shortcircuit -> {
ctx.combineTypes(lhsType, TyBool)
ctx.combineTypes(lhsType, TyBool)
TyBool
}
BinOpCategory.Shift -> lhsType
BinOpCategory.Math, BinOpCategory.Bitwise -> {
ctx.combineTypes(lhsType, rhsType)
lhsType
}
BinOpCategory.Comparison -> {
ctx.combineTypes(lhsType, rhsType)
TyBool
}
}
private fun inferTryExprType(expr: RsTryExpr): Ty {
val base = expr.expr.inferType() as? TyAdt ?: return TyUnknown
// TODO: make it work with generic `std::ops::Try` trait
if (base.item != items.Result && base.item != items.Option) return TyUnknown
TypeInferenceMarks.questionOperator.hit()
return base.typeArguments.getOrElse(0) { TyUnknown }
}
private fun inferTryMacroArgumentType(expr: RsExpr): Ty {
val base = expr.inferType() as? TyAdt ?: return TyUnknown
if (base.item != items.Result) return TyUnknown
return base.typeArguments.firstOrNull() ?: TyUnknown
}
private fun inferRangeType(expr: RsRangeExpr): Ty {
val el = expr.exprList
val dot2 = expr.dotdot
val dot3 = expr.dotdotdot ?: expr.dotdoteq
val (rangeName, indexType) = when {
dot2 != null && el.size == 0 -> "RangeFull" to null
dot2 != null && el.size == 1 -> {
val e = el[0]
if (e.startOffsetInParent < dot2.startOffsetInParent) {
"RangeFrom" to e.inferType()
} else {
"RangeTo" to e.inferType()
}
}
dot2 != null && el.size == 2 -> {
"Range" to getMoreCompleteType(el[0].inferType(), el[1].inferType())
}
dot3 != null && el.size == 1 -> {
val e = el[0]