-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Copy pathCheckCaptures.scala
1888 lines (1719 loc) · 88.8 KB
/
CheckCaptures.scala
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
package dotty.tools
package dotc
package cc
import core.*
import Phases.*, DenotTransformers.*, SymDenotations.*
import Contexts.*, Names.*, Flags.*, Symbols.*, Decorators.*
import Types.*, StdNames.*, Denotations.*
import config.Printers.{capt, recheckr, noPrinter}
import config.{Config, Feature}
import ast.{tpd, untpd, Trees}
import Trees.*
import typer.RefChecks.{checkAllOverrides, checkSelfAgainstParents, OverridingPairsChecker}
import typer.Checking.{checkBounds, checkAppliedTypesIn}
import typer.ErrorReporting.{Addenda, NothingToAdd, err}
import typer.ProtoTypes.{LhsProto, WildcardSelectionProto}
import util.{SimpleIdentitySet, EqHashMap, EqHashSet, SrcPos, Property}
import transform.{Recheck, PreRecheck, CapturedVars}
import Recheck.*
import scala.collection.mutable
import CaptureSet.{withCaptureSetsExplained, IdempotentCaptRefMap, CompareResult, CompareFailure, ExistentialSubsumesFailure}
import CCState.*
import StdNames.nme
import NameKinds.{DefaultGetterName, WildcardParamName, UniqueNameKind}
import reporting.{trace, Message, OverrideError}
import Annotations.Annotation
/** The capture checker */
object CheckCaptures:
import ast.tpd.*
val name: String = "cc"
val description: String = "capture checking"
enum EnvKind:
case Regular // normal case
case NestedInOwner // environment is a temporary one nested in the owner's environment,
// and does not have a different actual owner symbol
// (this happens when doing box adaptation).
case Boxed // environment is inside a box (in which case references are not counted)
/** A class describing environments.
* @param owner the current owner
* @param kind the environment's kind
* @param captured the capture set containing all references to tracked free variables outside of boxes
* @param outer0 the next enclosing environment
* @param nestedClosure under deferredReaches: If this is an env of a method with an anonymous function or
* anonymous class as RHS, the symbol of that function or class. NoSymbol in all other cases.
*/
case class Env(
owner: Symbol,
kind: EnvKind,
captured: CaptureSet,
outer0: Env | Null,
nestedClosure: Symbol = NoSymbol):
def outer = outer0.nn
def isOutermost = outer0 == null
/** If an environment is open it tracks free references */
def isOpen = !captured.isAlwaysEmpty && kind != EnvKind.Boxed
def outersIterator: Iterator[Env] = new:
private var cur = Env.this
def hasNext = !cur.isOutermost
def next(): Env =
val res = cur
cur = cur.outer
res
def ownerString(using Context): String =
if owner.isAnonymousFunction then "enclosing function" else owner.show
end Env
/** Similar normal substParams, but this is an approximating type map that
* maps parameters in contravariant capture sets to the empty set.
*/
final class SubstParamsMap(from: BindingType, to: List[Type])(using Context)
extends ApproximatingTypeMap, IdempotentCaptRefMap:
def apply(tp: Type): Type =
tp match
case tp: ParamRef =>
if tp.binder == from then to(tp.paramNum) else tp
case tp: NamedType =>
if tp.prefix `eq` NoPrefix then tp
else tp.derivedSelect(apply(tp.prefix))
case _: ThisType =>
tp
case _ =>
mapOver(tp)
override def toString = "SubstParamsMap"
end SubstParamsMap
/** Used for substituting parameters in a special case: when all actual arguments
* are mutually distinct capabilities.
*/
final class SubstParamsBiMap(from: LambdaType, to: List[Type])(using Context)
extends BiTypeMap:
thisMap =>
def apply(tp: Type): Type = tp match
case tp: ParamRef =>
if tp.binder == from then to(tp.paramNum) else tp
case tp: NamedType =>
if tp.prefix `eq` NoPrefix then tp
else tp.derivedSelect(apply(tp.prefix))
case _: ThisType =>
tp
case _ =>
mapOver(tp)
override def toString = "SubstParamsBiMap"
lazy val inverse = new BiTypeMap:
def apply(tp: Type): Type = tp match
case tp: NamedType =>
var idx = 0
var to1 = to
while idx < to.length && (tp ne to(idx)) do
idx += 1
to1 = to1.tail
if idx < to.length then from.paramRefs(idx)
else if tp.prefix `eq` NoPrefix then tp
else tp.derivedSelect(apply(tp.prefix))
case _: ThisType =>
tp
case _ =>
mapOver(tp)
override def toString = "SubstParamsBiMap.inverse"
def inverse = thisMap
end SubstParamsBiMap
/** A prototype that indicates selection with an immutable value */
class PathSelectionProto(val sym: Symbol, val pt: Type)(using Context) extends WildcardSelectionProto
/** Check that a @retains annotation only mentions references that can be tracked.
* This check is performed at Typer.
*/
def checkWellformed(parent: Tree, ann: Tree)(using Context): Unit =
def check(elem: Type, pos: SrcPos): Unit = elem match
case ref: CaptureRef =>
if !ref.isTrackableRef then
report.error(em"$elem cannot be tracked since it is not a parameter or local value", pos)
case tpe =>
report.error(em"$elem: $tpe is not a legal element of a capture set", pos)
for elem <- ann.retainedSet.retainedElements do
elem match
case ref: TypeRef =>
val refSym = ref.symbol
if refSym.isType && !refSym.info.derivesFrom(defn.Caps_CapSet) then
report.error(em"$elem is not a legal element of a capture set", ann.srcPos)
case ReachCapability(ref) =>
check(ref, ann.srcPos)
case ReadOnlyCapability(ref) =>
check(ref, ann.srcPos)
case _ =>
check(elem, ann.srcPos)
/** Under the sealed policy, report an error if some part of `tp` contains the
* root capability in its capture set or if it refers to a type parameter that
* could possibly be instantiated with cap in a way that's visible at the type.
*/
private def disallowRootCapabilitiesIn(tp: Type, carrier: Symbol, what: String, have: String, addendum: String, pos: SrcPos)(using Context) =
val check = new TypeTraverser:
private val seen = new EqHashSet[TypeRef]
// We keep track of open existential scopes here so that we can set these scopes
// in ccState when printing a part of the offending type.
var openExistentialScopes: List[MethodType] = Nil
def traverse(t: Type) =
t.dealiasKeepAnnots match
case t: TypeRef =>
if !seen.contains(t) then
seen += t
traverseChildren(t)
// Check the lower bound of path dependent types.
// See issue #19330.
val isMember = t.prefix ne NoPrefix
t.info match
case TypeBounds(lo, _) if isMember => traverse(lo)
case _ =>
case AnnotatedType(_, ann) if ann.symbol == defn.UncheckedCapturesAnnot =>
()
case CapturingType(parent, refs) =>
if variance >= 0 then
val openScopes = openExistentialScopes
refs.disallowRootCapability: () =>
def part =
if t eq tp then ""
else
// Show in context of all enclosing traversed existential scopes.
def showInOpenedFreshBinders(mts: List[MethodType]): String = mts match
case Nil => i"the part $t of "
case mt :: mts1 =>
CCState.inNewExistentialScope(mt):
showInOpenedFreshBinders(mts1)
showInOpenedFreshBinders(openScopes.reverse)
report.error(
em"""$what cannot $have $tp since
|${part}that type captures the root capability `cap`.$addendum""",
pos)
traverse(parent)
case defn.RefinedFunctionOf(mt) =>
traverse(mt)
case t: MethodType if t.marksExistentialScope =>
atVariance(-variance):
t.paramInfos.foreach(traverse)
val saved = openExistentialScopes
openExistentialScopes = t :: openExistentialScopes
try traverse(t.resType)
finally openExistentialScopes = saved
case t =>
traverseChildren(t)
check.traverse(tp)
end disallowRootCapabilitiesIn
trait CheckerAPI:
/** Complete symbol info of a val or a def */
def completeDef(tree: ValOrDefDef, sym: Symbol)(using Context): Type
extension [T <: Tree](tree: T)
/** Set new type of the tree if none was installed yet. */
def setNuType(tpe: Type): Unit
/** The new type of the tree, or if none was installed, the original type */
def nuType(using Context): Type
/** Was a new type installed for this tree? */
def hasNuType: Boolean
/** Is this tree passed to a parameter or assigned to a value with a type
* that contains cap in no-flip covariant position, which will necessite
* a separation check?
*/
def needsSepCheck: Boolean
/** If a tree is an argument for which needsSepCheck is true,
* the type of the formal paremeter corresponding to the argument.
*/
def formalType: Type
/** The "use set", i.e. the capture set marked as free at this node. */
def markedFree: CaptureSet
end CheckerAPI
class CheckCaptures extends Recheck, SymTransformer:
thisPhase =>
import ast.tpd.*
import CheckCaptures.*
override def phaseName: String = CheckCaptures.name
override def description: String = CheckCaptures.description
override def isRunnable(using Context) = super.isRunnable && Feature.ccEnabledSomewhere
def newRechecker()(using Context) = CaptureChecker(ctx)
override def run(using Context): Unit =
if Feature.ccEnabled then
super.run
val ccState1 = new CCState // Dotty problem: Rename to ccState ==> Crash in ExplicitOuter
class CaptureChecker(ictx: Context) extends Rechecker(ictx), CheckerAPI:
/** The current environment */
private val rootEnv: Env = inContext(ictx):
Env(defn.RootClass, EnvKind.Regular, CaptureSet.empty, null)
private var curEnv = rootEnv
/** Currently checked closures and their expected types, used for error reporting */
private var openClosures: List[(Symbol, Type)] = Nil
private val myCapturedVars: util.EqHashMap[Symbol, CaptureSet] = EqHashMap()
/** A list of actions to perform at postCheck. The reason to defer these actions
* is that it is sometimes better for type inference to not constrain too early
* with a checkConformsExpr.
*/
private val todoAtPostCheck = new mutable.ListBuffer[() => Unit]
/** Maps trees that need a separation check because they are arguments to
* polymorphic parameters. The trees are mapped to the formal parameter type.
*/
private val sepCheckFormals = util.EqHashMap[Tree, Type]()
private val usedSet = util.EqHashMap[Tree, CaptureSet]()
extension [T <: Tree](tree: T)
def needsSepCheck: Boolean = sepCheckFormals.contains(tree)
def formalType: Type = sepCheckFormals.getOrElse(tree, NoType)
def markedFree = usedSet.getOrElse(tree, CaptureSet.empty)
/** Instantiate capture set variables appearing contra-variantly to their
* upper approximation.
*/
private def interpolator(startingVariance: Int = 1)(using Context) = new TypeTraverser:
variance = startingVariance
override def traverse(t: Type) = t match
case t @ CapturingType(parent, refs) =>
refs match
case refs: CaptureSet.Var if variance < 0 => refs.solve()
case _ =>
traverse(parent)
case t @ defn.RefinedFunctionOf(rinfo) =>
traverse(rinfo)
case _ =>
traverseChildren(t)
/* Also set any previously unset owners of toplevel Fresh instances to improve
* error diagnostics in separation checking.
*/
private def anchorCaps(sym: Symbol)(using Context) = new TypeTraverser:
override def traverse(t: Type) =
if variance > 0 then
t match
case t @ CapturingType(parent, refs) =>
for ref <- refs.elems do
ref match
case root.Fresh(hidden) if !hidden.givenOwner.exists =>
hidden.givenOwner = sym
case _ =>
traverse(parent)
case t @ defn.RefinedFunctionOf(rinfo) =>
traverse(rinfo)
case _ =>
traverseChildren(t)
/** If `tpt` is an inferred type, interpolate capture set variables appearing contra-
* variantly in it. Also anchor Fresh instances with anchorCaps.
*/
private def interpolateVarsIn(tpt: Tree, sym: Symbol)(using Context): Unit =
if tpt.isInstanceOf[InferredTypeTree] then
interpolator().traverse(tpt.nuType)
.showing(i"solved vars in ${tpt.nuType}", capt)
anchorCaps(sym).traverse(tpt.nuType)
for msg <- ccState.approxWarnings do
report.warning(msg, tpt.srcPos)
ccState.approxWarnings.clear()
/** Assert subcapturing `cs1 <: cs2` (available for debugging, otherwise unused) */
def assertSub(cs1: CaptureSet, cs2: CaptureSet)(using Context) =
assert(cs1.subCaptures(cs2).isOK, i"$cs1 is not a subset of $cs2")
/** If `res` is not CompareResult.OK, report an error */
def checkOK(res: CompareResult, prefix: => String, added: CaptureRef | CaptureSet, pos: SrcPos, provenance: => String = "")(using Context): Unit =
res match
case res: CompareFailure =>
inContext(root.printContext(added, res.blocking)):
def toAdd: String = errorNotes(res.errorNotes).toAdd.mkString
def descr: String =
val d = res.blocking.description
if d.isEmpty then provenance else ""
report.error(em"$prefix included in the allowed capture set ${res.blocking}$descr$toAdd", pos)
case _ =>
/** Check subcapturing `{elem} <: cs`, report error on failure */
def checkElem(elem: CaptureRef, cs: CaptureSet, pos: SrcPos, provenance: => String = "")(using Context) =
checkOK(
ccState.test(elem.singletonCaptureSet.subCaptures(cs)),
i"$elem cannot be referenced here; it is not",
elem, pos, provenance)
/** Check subcapturing `cs1 <: cs2`, report error on failure */
def checkSubset(cs1: CaptureSet, cs2: CaptureSet, pos: SrcPos,
provenance: => String = "", cs1description: String = "")(using Context) =
checkOK(
ccState.test(cs1.subCaptures(cs2)),
if cs1.elems.size == 1 then i"reference ${cs1.elems.toList.head}$cs1description is not"
else i"references $cs1$cs1description are not all",
cs1, pos, provenance)
/** If `sym` is a class or method nested inside a term, a capture set variable representing
* the captured variables of the environment associated with `sym`.
*/
def capturedVars(sym: Symbol)(using Context): CaptureSet =
myCapturedVars.getOrElseUpdate(sym,
if sym.ownersIterator.exists(_.isTerm)
then CaptureSet.Var(sym.owner, level = sym.ccLevel)
else CaptureSet.empty)
// ---- Record Uses with MarkFree ----------------------------------------------------
/** The next environment enclosing `env` that needs to be charged
* with free references.
* @param included Whether an environment is included in the range of
* environments to charge. Once `included` is false, no
* more environments need to be charged.
*/
def nextEnvToCharge(env: Env, included: Env => Boolean)(using Context): Env =
if env.owner.isConstructor && included(env.outer) then env.outer.outer
else env.outer
/** A description where this environment comes from */
private def provenance(env: Env)(using Context): String =
val owner = env.owner
if owner.isAnonymousFunction then
val expected = openClosures
.find(_._1 == owner)
.map(_._2)
.getOrElse(owner.info.toFunctionType())
i"\nof an enclosing function literal with expected type $expected"
else
i"\nof the enclosing ${owner.showLocated}"
/** Does the given environment belong to a method that is (a) nested in a term
* and (b) not the method of an anonympus function?
*/
def isOfNestedMethod(env: Env | Null)(using Context) =
env != null
&& env.owner.is(Method)
&& env.owner.owner.isTerm
&& !env.owner.isAnonymousFunction
/** Include `sym` in the capture sets of all enclosing environments nested in the
* the environment in which `sym` is defined.
*/
def markFree(sym: Symbol, tree: Tree)(using Context): Unit =
markFree(sym, sym.termRef, tree)
def markFree(sym: Symbol, ref: CaptureRef, tree: Tree)(using Context): Unit =
if sym.exists && ref.isTracked then markFree(ref.captureSet, tree)
/** Make sure the (projected) `cs` is a subset of the capture sets of all enclosing
* environments. At each stage, only include references from `cs` that are outside
* the environment's owner
*/
def markFree(cs: CaptureSet, tree: Tree)(using Context): Unit =
// A captured reference with the symbol `sym` is visible from the environment
// if `sym` is not defined inside the owner of the environment.
inline def isVisibleFromEnv(sym: Symbol, env: Env) =
sym.exists && {
if env.kind == EnvKind.NestedInOwner then
!sym.isProperlyContainedIn(env.owner)
else
!sym.isContainedIn(env.owner)
}
/** If captureRef `c` refers to a parameter that is not @use declared, report an error.
* Exception under deferredReaches: If use comes from a nested closure, accept it.
*/
def checkUseDeclared(c: CaptureRef, env: Env, lastEnv: Env | Null) =
if lastEnv != null && env.nestedClosure.exists && env.nestedClosure == lastEnv.owner then
assert(ccConfig.deferredReaches) // access is from a nested closure under deferredReaches, so it's OK
else c.pathRoot match
case ref: NamedType if !ref.symbol.isUseParam =>
val what = if ref.isType then "Capture set parameter" else "Local reach capability"
report.error(
em"""$what $c leaks into capture scope of ${env.ownerString}.
|To allow this, the ${ref.symbol} should be declared with a @use annotation""", tree.srcPos)
case _ =>
/** Avoid locally defined capability by charging the underlying type
* (which may not be cap). This scheme applies only under the deferredReaches setting.
*/
def avoidLocalCapability(c: CaptureRef, env: Env, lastEnv: Env | Null): Unit =
if c.isParamPath then
c match
case ReachCapability(_) | _: TypeRef =>
checkUseDeclared(c, env, lastEnv)
case _ =>
else
val underlying = c match
case ReachCapability(c1) =>
CaptureSet.ofTypeDeeply(c1.widen)
case _ =>
CaptureSet.ofType(c.widen, followResult = false)
capt.println(i"Widen reach $c to $underlying in ${env.owner}")
underlying.disallowRootCapability: () =>
report.error(em"Local capability $c in ${env.ownerString} cannot have `cap` as underlying capture set", tree.srcPos)
recur(underlying, env, lastEnv)
/** Avoid locally defined capability if it is a reach capability or capture set
* parameter. This is the default.
*/
def avoidLocalReachCapability(c: CaptureRef, env: Env): Unit = c match
case ReachCapability(c1) =>
if c1.isParamPath then
checkUseDeclared(c, env, null)
else
// When a reach capabilty x* where `x` is not a parameter goes out
// of scope, we need to continue with `x`'s underlying deep capture set.
// It is an error if that set contains cap.
// The same is not an issue for normal capabilities since in a local
// definition `val x = e`, the capabilities of `e` have already been charged.
// Note: It's not true that the underlying capture set of a reach capability
// is always cap. Reach capabilities over paths depend on the prefix, which
// might turn a cap into something else.
// The path-use.scala neg test contains an example.
val underlying = CaptureSet.ofTypeDeeply(c1.widen)
capt.println(i"Widen reach $c to $underlying in ${env.owner}")
if ccConfig.useSepChecks then
recur(underlying.filter(!_.isRootCapability), env, null)
// we don't want to disallow underlying Fresh instances, since these are typically locally created
// fresh capabilities. We don't need to also follow the hidden set since separation
// checking makes ure that locally hidden references need to go to @consume parameters.
else
underlying.disallowRootCapability: () =>
report.error(em"Local reach capability $c leaks into capture scope of ${env.ownerString}", tree.srcPos)
recur(underlying, env, null)
case c: TypeRef if c.isParamPath =>
checkUseDeclared(c, env, null)
case _ =>
def recur(cs: CaptureSet, env: Env, lastEnv: Env | Null): Unit =
if env.isOpen && !env.owner.isStaticOwner && !cs.isAlwaysEmpty then
// Only captured references that are visible from the environment
// should be included.
val included = cs.filter: c =>
val isVisible = isVisibleFromEnv(c.pathOwner, env)
if !isVisible then
if ccConfig.deferredReaches
then avoidLocalCapability(c, env, lastEnv)
else avoidLocalReachCapability(c, env)
isVisible
checkSubset(included, env.captured, tree.srcPos, provenance(env))
capt.println(i"Include call or box capture $included from $cs in ${env.owner} --> ${env.captured}")
if !isOfNestedMethod(env) then
recur(included, nextEnvToCharge(env, !_.owner.isStaticOwner), env)
// Don't propagate out of methods inside terms. The use set of these methods
// will be charged when that method is called.
recur(cs, curEnv, null)
usedSet(tree) = tree.markedFree ++ cs
end markFree
/** Include references captured by the called method in the current environment stack */
def includeCallCaptures(sym: Symbol, resType: Type, tree: Tree)(using Context): Unit = resType match
case _: MethodOrPoly => // wait until method is fully applied
case _ =>
def isRetained(ref: CaptureRef): Boolean = ref.pathRoot match
case root: ThisType => ctx.owner.isContainedIn(root.cls)
case _ => true
if sym.exists && curEnv.isOpen then
markFree(capturedVars(sym).filter(isRetained), tree)
/** Under the sealed policy, disallow the root capability in type arguments.
* Type arguments come either from a TypeApply node or from an AppliedType
* which represents a trait parent in a template.
* Also, if a corresponding formal type parameter is declared or implied @use,
* charge the deep capture set of the argument to the environent.
* @param fn the type application, of type TypeApply or TypeTree
* @param sym the constructor symbol (could be a method or a val or a class)
* @param args the type arguments
*/
def disallowCapInTypeArgs(fn: Tree, sym: Symbol, args: List[Tree])(using Context): Unit =
def isExempt = sym.isTypeTestOrCast || sym == defn.Compiletime_erasedValue
if !isExempt then
val paramNames = atPhase(thisPhase.prev):
fn.tpe.widenDealias match
case tl: TypeLambda => tl.paramNames
case ref: AppliedType if ref.typeSymbol.isClass => ref.typeSymbol.typeParams.map(_.name)
case t =>
println(i"parent type: $t")
args.map(_ => EmptyTypeName)
for case (arg: TypeTree, pname) <- args.lazyZip(paramNames) do
def where = if sym.exists then i" in an argument of $sym" else ""
val (addendum, errTree) =
if arg.isInferred
then ("\nThis is often caused by a local capability$where\nleaking as part of its result.", fn)
else if arg.span.exists then ("", arg)
else ("", fn)
disallowRootCapabilitiesIn(arg.nuType, NoSymbol,
i"Type variable $pname of $sym", "be instantiated to", addendum, errTree.srcPos)
val param = fn.symbol.paramNamed(pname)
if param.isUseParam then markFree(arg.nuType.deepCaptureSet, errTree)
end disallowCapInTypeArgs
/** Rechecking idents involves:
* - adding call captures for idents referring to methods
* - marking as free the identifier with any selections or .rd
* modifiers implied by the expected type
*/
override def recheckIdent(tree: Ident, pt: Type)(using Context): Type =
val sym = tree.symbol
if sym.is(Method) then
// If ident refers to a parameterless method, charge its cv to the environment
includeCallCaptures(sym, sym.info, tree)
else if !sym.isStatic then
// Otherwise charge its symbol, but add all selections and also any `.rd`
// modifier implied by the expected type `pt`.
// Example: If we have `x` and the expected type says we select that with `.a.b`
// where `b` is a read-only method, we charge `x.a.b.rd` instead of `x`.
def addSelects(ref: TermRef, pt: Type): CaptureRef = pt match
case pt: PathSelectionProto if ref.isTracked =>
if pt.sym.isReadOnlyMethod then
ref.readOnly
else
// if `ref` is not tracked then the selection could not give anything new
// class SerializationProxy in stdlib-cc/../LazyListIterable.scala has an example where this matters.
addSelects(ref.select(pt.sym).asInstanceOf[TermRef], pt.pt)
case _ => ref
var pathRef: CaptureRef = addSelects(sym.termRef, pt)
if pathRef.derivesFrom(defn.Caps_Mutable) && pt.isValueType && !pt.isMutableType then
pathRef = pathRef.readOnly
markFree(sym, pathRef, tree)
super.recheckIdent(tree, pt)
/** The expected type for the qualifier of a selection. If the selection
* could be part of a capability path or is a a read-only method, we return
* a PathSelectionProto.
*/
override def selectionProto(tree: Select, pt: Type)(using Context): Type =
val sym = tree.symbol
if !sym.isOneOf(UnstableValueFlags) && !sym.isStatic
|| sym.isReadOnlyMethod
then PathSelectionProto(sym, pt)
else super.selectionProto(tree, pt)
/** A specialized implementation of the selection rule.
*
* E |- f: T{ m: R^Cr }^{f}
* ------------------------
* E |- f.m: R^C
*
* The implementation picks as `C` one of `{f}` or `Cr`, depending on the
* outcome of a `mightSubcapture` test. It picks `{f}` if it might subcapture Cr
* and picks Cr otherwise.
*/
override def recheckSelection(tree: Select, qualType: Type, name: Name, pt: Type)(using Context) = {
def disambiguate(denot: Denotation): Denotation = denot match
case MultiDenotation(denot1, denot2) =>
// This case can arise when we try to merge multiple types that have different
// capture sets on some part. For instance an asSeenFrom might produce
// a bi-mapped capture set arising from a substition. Applying the same substitution
// to the same type twice will nevertheless produce different capture sets which can
// lead to a failure in disambiguation since neither alternative is better than the
// other in a frozen constraint. An example test case is disambiguate-select.scala.
// We address the problem by disambiguating while ignoring all capture sets as a fallback.
withMode(Mode.IgnoreCaptures) {
disambiguate(denot1).meet(disambiguate(denot2), qualType)
}
case _ => denot
// Don't allow update methods to be called unless the qualifier captures
// an exclusive reference. TODO This should probably rolled into
// qualifier logic once we have it.
if tree.symbol.isUpdateMethod && !qualType.captureSet.isExclusive then
report.error(
em"""cannot call update ${tree.symbol} from $qualType,
|since its capture set ${qualType.captureSet} is read-only""",
tree.srcPos)
val selType = recheckSelection(tree, qualType, name, disambiguate)
val selWiden = selType.widen
// Don't apply the rule
// - on the LHS of assignments, or
// - if the qualifier or selection type is boxed, or
// - the selection is either a trackable capture ref or a pure type
if noWiden(selType, pt)
|| qualType.isBoxedCapturing
|| selWiden.isBoxedCapturing
|| selType.isTrackableRef
|| selWiden.captureSet.isAlwaysEmpty
then
selType
else
val qualCs = qualType.captureSet
val selCs = selType.captureSet
capt.println(i"pick one of $qualType, ${selType.widen}, $qualCs, $selCs ${selWiden.captureSet} in $tree")
if qualCs.mightSubcapture(selCs)
//&& !selCs.mightSubcapture(qualCs)
&& !pt.stripCapturing.isInstanceOf[SingletonType]
then
selWiden.stripCapturing.capturing(qualCs)
.showing(i"alternate type for select $tree: $selType --> $result, $qualCs / $selCs", capt)
else
selType
}//.showing(i"recheck sel $tree, $qualType = $result")
/** Hook for massaging a function before it is applied. Copies all @use and @consume
* annotations on method parameter symbols to the corresponding paramInfo types.
*/
override def prepareFunction(funtpe: MethodType, meth: Symbol)(using Context): MethodType =
val paramInfosWithUses =
funtpe.paramInfos.zipWithConserve(funtpe.paramNames): (formal, pname) =>
val param = meth.paramNamed(pname)
def copyAnnot(tp: Type, cls: ClassSymbol) = param.getAnnotation(cls) match
case Some(ann) => AnnotatedType(tp, ann)
case _ => tp
copyAnnot(copyAnnot(formal, defn.UseAnnot), defn.ConsumeAnnot)
funtpe.derivedLambdaType(paramInfos = paramInfosWithUses)
/** Recheck applications, with special handling of unsafeAssumePure.
* More work is done in `recheckApplication`, `recheckArg` and `instantiate` below.
*/
override def recheckApply(tree: Apply, pt: Type)(using Context): Type =
val meth = tree.fun.symbol
if meth == defn.Caps_unsafeAssumePure then
val arg :: Nil = tree.args: @unchecked
val argType0 = recheck(arg, pt.stripCapturing.capturing(root.Fresh()))
val argType =
if argType0.captureSet.isAlwaysEmpty then argType0
else argType0.widen.stripCapturing
capt.println(i"rechecking unsafeAssumePure of $arg with $pt: $argType")
super.recheckFinish(argType, tree, pt)
else
val res = super.recheckApply(tree, pt)
includeCallCaptures(meth, res, tree)
res
/** Recheck argument against a "freshened" version of `formal` where toplevel `cap`
* occurrences are replaced by `Fresh` instances. Also, if formal parameter carries a `@use`,
* charge the deep capture set of the actual argument to the environment.
*/
protected override def recheckArg(arg: Tree, formal: Type)(using Context): Type =
val freshenedFormal = root.capToFresh(formal)
val argType = recheck(arg, freshenedFormal)
.showing(i"recheck arg $arg vs $freshenedFormal", capt)
if formal.hasAnnotation(defn.UseAnnot) || formal.hasAnnotation(defn.ConsumeAnnot) then
// The @use and/or @consume annotation is added to `formal` by `prepareFunction`
capt.println(i"charging deep capture set of $arg: ${argType} = ${argType.deepCaptureSet}")
markFree(argType.deepCaptureSet, arg)
if formal.containsCap then
sepCheckFormals(arg) = freshenedFormal
argType
/** Map existential captures in result to `cap` and implement the following
* rele:
*
* E |- q: Tq^Cq
* E |- q.f: Ta^Ca ->Cf Tr^Cr
* E |- a: Ta
* ---------------------
* E |- f(a): Tr^C
*
* If the function `f` does not have an `@use` parameter, then
* any unboxing it does would be charged to the environment of the function
* so they have to appear in Cq. Since any capabilities of the result of the
* application must already be present in the application, an upper
* approximation of the result capture set is Cq \union Ca, where `Ca`
* is the capture set of the argument.
* If the function `f` does have an `@use` parameter, then it could in addition
* unbox reach capabilities over its formal parameter. Therefore, the approximation
* would be `Cq \union dcs(Ta)` instead.
* If the approximation might subcapture the declared result Cr, we pick it for C
* otherwise we pick Cr.
*/
protected override
def recheckApplication(tree: Apply, qualType: Type, funType: MethodType, argTypes: List[Type])(using Context): Type =
val appType = root.resultToFresh(super.recheckApplication(tree, qualType, funType, argTypes))
val qualCaptures = qualType.captureSet
val argCaptures =
for (argType, formal) <- argTypes.lazyZip(funType.paramInfos) yield
if formal.hasAnnotation(defn.UseAnnot) then argType.deepCaptureSet else argType.captureSet
appType match
case appType @ CapturingType(appType1, refs)
if qualType.exists
&& !tree.fun.symbol.isConstructor
&& qualCaptures.mightSubcapture(refs)
&& argCaptures.forall(_.mightSubcapture(refs)) =>
val callCaptures = argCaptures.foldLeft(qualCaptures)(_ ++ _)
appType.derivedCapturingType(appType1, callCaptures)
.showing(i"narrow $tree: $appType, refs = $refs, qual-cs = ${qualType.captureSet} = $result", capt)
case appType =>
appType
private def isDistinct(xs: List[Type]): Boolean = xs match
case x :: xs1 => xs1.isEmpty || !xs1.contains(x) && isDistinct(xs1)
case Nil => true
/** Handle an application of method `sym` with type `mt` to arguments of types `argTypes`.
* This means
* - Instantiate result type with actual arguments
* - if `sym` is a constructor, refine its type with `refineInstanceType`
* If all argument types are mutually different trackable capture references, use a BiTypeMap,
* since that is more precise. Otherwise use a normal idempotent map, which might lose information
* in the case where the result type contains captureset variables that are further
* constrained afterwards.
*/
override def instantiate(mt: MethodType, argTypes: List[Type], sym: Symbol)(using Context): Type =
val ownType =
if !mt.isResultDependent then
mt.resType
else if argTypes.forall(_.isTrackableRef) && isDistinct(argTypes) then
SubstParamsBiMap(mt, argTypes)(mt.resType)
else
SubstParamsMap(mt, argTypes)(mt.resType)
if sym.isConstructor then refineConstructorInstance(ownType, mt, argTypes, sym)
else ownType
/** Refine the type returned from a constructor as follows:
* - remember types of arguments corresponding to tracked parameters in refinements.
* - add capture set of instantiated class and capture set of constructor to capture set of result type.
* Note: This scheme does not distinguish whether a capture is made by the constructor
* only or by a method in the class. Both captures go into the result type. We
* could be more precise by distinguishing the two capture sets.
*/
private def refineConstructorInstance(resType: Type, mt: MethodType, argTypes: List[Type], constr: Symbol)(using Context): Type =
val cls = constr.owner.asClass
/** First half of result pair:
* Refine the type of a constructor call `new C(t_1, ..., t_n)`
* to C{val x_1: @refineOverride T_1, ..., x_m: @refineOverride T_m}
* where x_1, ..., x_m are the tracked parameters of C and
* T_1, ..., T_m are the types of the corresponding arguments. The @refineOveride
* annotations avoid problematic intersections of capture sets when those
* parameters are selected.
*
* Second half: union of initial capture set and all capture sets of arguments
* to tracked parameters. The initial capture set `initCs` is augmented with
* - root.Fresh(...) if `core` extends Mutable
* - root.Fresh(...).rd if `core` extends Capability
*/
def addParamArgRefinements(core: Type, initCs: CaptureSet): (Type, CaptureSet) =
var refined: Type = core
var allCaptures: CaptureSet =
if core.derivesFromMutable then initCs ++ CaptureSet.fresh()
else if core.derivesFromCapability then initCs ++ root.Fresh.withOwner(core.classSymbol).readOnly.singletonCaptureSet
else initCs
for (getterName, argType) <- mt.paramNames.lazyZip(argTypes) do
val getter = cls.info.member(getterName).suchThat(_.isRefiningParamAccessor).symbol
if !getter.is(Private) && getter.hasTrackedParts then
refined = RefinedType(refined, getterName,
AnnotatedType(argType.unboxed, Annotation(defn.RefineOverrideAnnot, util.Spans.NoSpan))) // Yichen you might want to check this
allCaptures ++= argType.captureSet
(refined, allCaptures)
/** Augment result type of constructor with refinements and captures.
* @param core The result type of the constructor
* @param initCs The initial capture set to add, not yet counting capture sets from arguments
*/
def augmentConstructorType(core: Type, initCs: CaptureSet): Type = core match
case core: MethodType =>
// more parameters to follow; augment result type
core.derivedLambdaType(resType = augmentConstructorType(core.resType, initCs))
case CapturingType(parent, refs) =>
// can happen for curried constructors if instantiate of a previous step
// added capture set to result.
augmentConstructorType(parent, initCs ++ refs)
case _ =>
val (refined, cs) = addParamArgRefinements(core, initCs)
refined.capturing(cs)
augmentConstructorType(resType, capturedVars(cls) ++ capturedVars(constr))
.showing(i"constr type $mt with $argTypes%, % in $constr = $result", capt)
end refineConstructorInstance
/** Recheck type applications:
* - Map existential captures in result to `cap`
* - include captures of called methods in environment
* - don't allow cap to appear covariantly in type arguments
* - special handling of `contains[A, B]` calls
*/
override def recheckTypeApply(tree: TypeApply, pt: Type)(using Context): Type =
val meth = tree.fun match
case fun @ Select(qual, nme.apply) => qual.symbol.orElse(fun.symbol)
case fun => fun.symbol
disallowCapInTypeArgs(tree.fun, meth, tree.args)
val res = root.resultToFresh(super.recheckTypeApply(tree, pt))
includeCallCaptures(tree.symbol, res, tree)
checkContains(tree)
res
end recheckTypeApply
/** Faced with a tree of form `caps.contansImpl[CS, r.type]`, check that `R` is a tracked
* capability and assert that `{r} <: CS`.
*/
def checkContains(tree: TypeApply)(using Context): Unit = tree match
case ContainsImpl(csArg, refArg) =>
val cs = csArg.nuType.captureSet
val ref = refArg.nuType
capt.println(i"check contains $cs , $ref")
ref match
case ref: CaptureRef if ref.isTracked =>
checkElem(ref, cs, tree.srcPos)
case _ =>
report.error(em"$refArg is not a tracked capability", refArg.srcPos)
case _ =>
override def recheckBlock(tree: Block, pt: Type)(using Context): Type =
inNestedLevel(super.recheckBlock(tree, pt))
/** Recheck Closure node: add the captured vars of the anonymoys function
* to the result type. See also `recheckClosureBlock` which rechecks the
* block containing the anonymous function and the Closure node.
*/
override def recheckClosure(tree: Closure, pt: Type, forceDependent: Boolean)(using Context): Type =
val cs = capturedVars(tree.meth.symbol)
capt.println(i"typing closure $tree with cvs $cs")
super.recheckClosure(tree, pt, forceDependent).capturing(cs)
.showing(i"rechecked closure $tree / $pt = $result", capt)
/** Recheck a lambda of the form
* { def $anonfun(...) = ...; closure($anonfun, ...)}
*/
override def recheckClosureBlock(mdef: DefDef, expr: Closure, pt: Type)(using Context): Type =
openClosures = (mdef.symbol, pt) :: openClosures
try
// Constrain closure's parameters and result from the expected type before
// rechecking the body.
val res = recheckClosure(expr, pt, forceDependent = true)
if !(isEtaExpansion(mdef) && ccConfig.handleEtaExpansionsSpecially) then
// Check whether the closure's results conforms to the expected type
// This constrains parameter types of the closure which can give better
// error messages.
// But if the closure is an eta expanded method reference it's better to not constrain
// its internals early since that would give error messages in generated code
// which are less intelligible. An example is the line `a = x` in
// neg-custom-args/captures/vars.scala. That's why this code is conditioned.
// to apply only to closures that are not eta expansions.
val res1 = root.resultToFresh(res) // TODO: why deep = true?
val pt1 = root.resultToFresh(pt)
// We need to open existentials here in order not to get vars mixed up in them
// We do the proper check with existentials when we are finished with the closure block.
capt.println(i"pre-check closure $expr of type $res1 against $pt1")
checkConformsExpr(res1, pt1, expr)
recheckDef(mdef, mdef.symbol)
res
finally
openClosures = openClosures.tail
end recheckClosureBlock
/** Elements of a SeqLiteral instantiate a Seq or Array parameter, so they
* should be boxed.
*/
override def seqLiteralElemProto(tree: SeqLiteral, pt: Type, declared: Type)(using Context) =
super.seqLiteralElemProto(tree, pt, declared).boxed
/** Recheck val and var definitions:
* - disallow cap in the type of mutable vars.
* - for externally visible definitions: check that their inferred type
* does not refine what was known before capture checking.
* - Interpolate contravariant capture set variables in result type.
*/
override def recheckValDef(tree: ValDef, sym: Symbol)(using Context): Type =
try
if sym.is(Module) then sym.info // Modules are checked by checking the module class
else
if sym.is(Mutable) && !sym.hasAnnotation(defn.UncheckedCapturesAnnot) then
val (carrier, addendum) = capturedBy.get(sym) match
case Some(encl) =>
val enclStr =
if encl.isAnonymousFunction then
val location = anonFunCallee.get(encl) match
case Some(meth) if meth.exists => i" argument in a call to $meth"
case _ => ""
s"an anonymous function$location"
else encl.show
(NoSymbol, i"\n\nNote that $sym does not count as local since it is captured by $enclStr")
case _ =>
(sym, "")
disallowRootCapabilitiesIn(
tree.tpt.nuType, carrier, i"Mutable $sym", "have type", addendum, sym.srcPos)
checkInferredResult(super.recheckValDef(tree, sym), tree)
finally
if !sym.is(Param) then
// Parameters with inferred types belong to anonymous methods. We need to wait
// for more info from the context, so we cannot interpolate. Note that we cannot
// expect to have all necessary info available at the point where the anonymous
// function is compiled since we do not propagate expected types into blocks.
interpolateVarsIn(tree.tpt, sym)
/** Recheck method definitions:
* - check body in a nested environment that tracks uses, in a nested level,
* and in a nested context that knows abaout Contains parameters so that we
* can assume they are true.
* - for externally visible definitions: check that their inferred type
* does not refine what was known before capture checking.
* - Interpolate contravariant capture set variables in result type unless
* def is anonymous.
*/
override def recheckDefDef(tree: DefDef, sym: Symbol)(using Context): Type =
if Synthetics.isExcluded(sym) then sym.info
else
// Under the deferredReaches setting: If rhs ends in a closure or
// anonymous class, the corresponding symbol
def nestedClosure(rhs: Tree)(using Context): Symbol =
if !ccConfig.deferredReaches then NoSymbol
else rhs match
case Closure(_, meth, _) => meth.symbol
case Apply(fn, _) if fn.symbol.isConstructor && fn.symbol.owner.isAnonymousClass => fn.symbol.owner
case Block(_, expr) => nestedClosure(expr)
case Inlined(_, _, expansion) => nestedClosure(expansion)
case Typed(expr, _) => nestedClosure(expr)
case _ => NoSymbol
val saved = curEnv
val localSet = capturedVars(sym)
if !localSet.isAlwaysEmpty then
curEnv = Env(sym, EnvKind.Regular, localSet, curEnv, nestedClosure(tree.rhs))
// ctx with AssumedContains entries for each Contains parameter
val bodyCtx =
var ac = CaptureSet.assumedContains
for paramSyms <- sym.paramSymss do
for case ContainsParam(cs, ref) <- paramSyms do
ac = ac.updated(cs, ac.getOrElse(cs, SimpleIdentitySet.empty) + ref)
if ac.isEmpty then ctx