-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathCheckCaptures.scala
More file actions
2487 lines (2258 loc) · 117 KB
/
CheckCaptures.scala
File metadata and controls
2487 lines (2258 loc) · 117 KB
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.ForceDegree
import typer.Inferencing.isFullyDefined
import typer.RefChecks.{checkAllOverrides, checkSelfAgainstParents, OverridingPairsChecker}
import typer.Checking.{checkBounds, checkAppliedTypesIn}
import typer.ErrorReporting.err
import typer.ProtoTypes.{LhsProto, WildcardSelectionProto, SelectionProto}
import util.{SimpleIdentitySet, EqHashMap, EqHashSet, SrcPos, Property}
import util.chaining.tap
import transform.{Recheck, PreRecheck, CapturedVars}
import Recheck.*
import scala.collection.mutable
import CaptureSet.{withCaptureSetsExplained, IncludeFailure, MutAdaptFailure, VarState}
import CCState.*
import StdNames.nme
import NameKinds.{DefaultGetterName, WildcardParamName, UniqueNameKind}
import NameOps.isReplWrapperName
import reporting.*
import reporting.Message.Note
import Annotations.Annotation
import Constants.Constant
import Capabilities.*
import Mutability.*
import util.common.alwaysTrue
import scala.annotation.constructorOnly
/** The capture checker */
object CheckCaptures:
import ast.tpd.*
val name: String = "cc"
val description: String = "capture checking"
/** An attachment to prevent widening of arguments to tracked parameters */
val NoWiden: Property.Key[Unit] = Property.Key()
enum EnvKind derives CanEqual:
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.
*/
class Env(
val owner: Symbol,
val kind: EnvKind,
val captured: CaptureSet,
val outer0: Env | Null,
val nestedClosure: Symbol = NoSymbol)(using @constructorOnly ictx: Context) {
assert(definesEnv(owner))
captured match
case captured: CaptureSet.Var => assert(captured.owner == owner,
i"owner discrepancy env owner = $owner but its captureset $captured has owner ${captured.owner}")
case _ =>
def outer = outer0.nn
def isRoot(using Context) = owner.is(Package)
def outersIterator(using Context): Iterator[Env] = new:
private var cur = Env.this
def hasNext = !cur.isRoot
def next(): Env =
val res = cur
cur = cur.outer
res
}
def definesEnv(sym: Symbol)(using Context): Boolean =
sym.isOneOf(MethodOrLazy) || sym.isClass
/** 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 {
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"
}
/** Check that a @retains annotation only mentions references that can be tracked.
* This check is performed at Typer.
*/
def checkWellformedRetains(parent: Tree, ann: Tree)(using Context): Unit =
def check(elem: Type): Unit = elem match
case ref: TypeRef =>
val refSym = ref.symbol
if refSym.isType && !refSym.info.derivesFromCapSet then
report.error(em"$elem is not a legal element of a capture set", ann.srcPos)
case ref: CoreCapability =>
if !ref.isTrackableRef && !ref.isLocalMutable then
report.error(em"$elem cannot be tracked since it is not a parameter or local value", ann.srcPos)
case ReachCapability(ref) =>
check(ref)
if ref.isCapsAnyRef || ref.isCapsFreshRef then
report.error(em"Cannot form a reach capability from `${ref.termSymbol.name}`", ann.srcPos)
case ReadOnlyCapability(ref) =>
check(ref)
case OnlyCapability(ref, cls) =>
if !cls.isClassifiedCapabilityClass then
report.error(
em"""${ref.showRef}.only[${cls.name}] is not well-formed since $cls is not a classifier class.
|A classifier class is a class extending `caps.Capability` and directly extending `caps.Classifier`.""",
ann.srcPos)
check(ref)
case elem =>
report.error(em"$elem is not a legal element of a capture set", ann.srcPos)
ann.retainedSet.retainedElementsRaw.foreach(check)
/** Disallow bad roots anywhere in type `tp``.
* @param upto controls up to which owner local LocalCap capabilities should be disallowed.
* See disallowBadRoots for details.
*/
private def disallowBadRootsIn(tp: Type, upto: 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.disallowBadRoots(upto): () =>
def part =
if t eq tp then ""
else
// Show in context of all enclosing traversed existential scopes.
def showInOpenedResultBinders(mts: List[MethodType]): String = mts match
case Nil => i"the part $t of "
case mt :: mts1 =>
inNewExistentialScope(mt):
showInOpenedResultBinders(mts1)
showInOpenedResultBinders(openScopes.reverse)
report.error(
em"""$what cannot $have $tp since
|${part}that type captures the root capability `any`.$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)
}
private def contributesLocalCapToClass(sym: Symbol)(using Context): Boolean =
sym.isField
&& !sym.isOneOf(DeferredOrTermParamOrAccessor)
&& !sym.hasAnnotation(defn.UntrackedCapturesAnnot)
trait CheckerAPI:
/** Complete symbol info of a val or a def */
def completeDef(tree: ValOrDefDef, sym: Symbol, completer: LazyType)(using Context): Unit
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 `any` 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 parameter 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
/** We normally need a recompute if the prefix is a SingletonType and the
* last denotation is not a SymDenotation. The SingletonType requirement is
* so that we don't widen TermRefs with non-path prefixes to their underlying
* type when recomputing their denotations with asSeenFrom. Such widened types
* would become illegal members of capture sets.
*
* The SymDenotation requirement is so that we don't recompute termRefs of Symbols
* which should be handled by SymTransformers alone. However, if the underlying type
* of the prefix is a capturing type, we do need to recompute since in that case
* the prefix might carry a parameter refinement created in Setup, and we need to
* take these refinements into account.
*/
override def needsRecompute(tp: NamedType, lastDenotation: SingleDenotation)(using Context): Boolean =
tp.prefix match
case prefix: TermRef =>
!lastDenotation.isInstanceOf[SymDenotation]
|| !prefix.info.captureSet.isAlwaysEmpty
case prefix: SingletonType =>
!lastDenotation.isInstanceOf[SymDenotation]
case _ =>
false
def newRechecker()(using Context) = CaptureChecker(ctx)
override protected 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:
// println(i"checking ${ictx.source}"(using ictx))
/** 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
/** 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]()
/** The references used at identifier or application trees, including the
* environment at the reference point.
*/
private val useInfos = mutable.ArrayBuffer[(Tree, CaptureSet, Env)]()
private val usedSet = util.EqHashMap[Tree, CaptureSet]()
/** The set of symbols that were rechecked via a completer */
private val completed = new mutable.HashSet[Symbol]
private var needAnotherRun = false
def resetIteration()(using Context): Unit =
needAnotherRun = false
resetNuTypes()
todoAtPostCheck.clear()
completed.clear()
extension [T <: Tree](tree: T)
def needsSepCheck: Boolean = sepCheckFormals.contains(tree)
def formalType: Type = sepCheckFormals.getOrElse(tree, NoType)
def markedFree: CaptureSet = usedSet.getOrElse(tree, CaptureSet.empty)
/** Instantiate capture set variables appearing contra-variantly to their
* upper approximation.
*/
private def interpolate(tp: Type, sym: Symbol, startingVariance: Int = 1)(using Context): Unit =
object variances extends TypeTraverser:
variance = startingVariance
val varianceOfVar = EqHashMap[CaptureSet.Var, Int]()
override def traverse(t: Type) = t match
case t @ CapturingType(parent, refs) =>
refs match
case refs: CaptureSet.Var if !refs.isConst =>
varianceOfVar(refs) = varianceOfVar.get(refs) match
case Some(v0) => if v0 == 0 then 0 else (v0 + variance) / 2
case None => variance
case _ =>
traverse(parent)
case t @ defn.RefinedFunctionOf(rinfo) =>
traverse(rinfo)
case _ =>
traverseChildren(t)
val interpolator = new TypeTraverser:
override def traverse(t: Type) = t match
case t @ CapturingType(parent, refs) =>
refs match
case refs: CaptureSet.Var if !refs.isConst =>
if variances.varianceOfVar(refs) < 0 then refs.solve()
else refs.markSolved(provisional = !sym.isMutableVar)
case _ =>
traverse(parent)
case t @ defn.RefinedFunctionOf(rinfo) =>
traverse(rinfo)
case _ =>
traverseChildren(t)
variances.traverse(tp)
interpolator.traverse(tp)
end interpolate
/* Also set any previously unset owners of toplevel LocalCap 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) =>
refs match
case refs: CaptureSet.VarInTypeTree if refs.owner == sym =>
refs.normalizeLocalCaps()
case _ =>
for ref <- refs.elems do
ref match
case ref: LocalCap if !ref.hiddenSet.givenOwner.exists =>
ref.hiddenSet.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 LocalCap instances with anchorCaps.
* Note: module vals don't have inferred types but still hold capture set variables.
* These capture set variables are interpolated after the associated module class
* has been rechecked.
*/
private def interpolateIfInferred(tpt: Tree, sym: Symbol)(using Context): Unit =
if tpt.isInstanceOf[InferredTypeTree] then
interpolate(tpt.nuType, sym)
.showing(i"solved vars for $sym 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), i"$cs1 is not a subset of $cs2")
/** A note that explains why a reference to a static owner is a capability */
class WhyCapability(elem: Capability) extends Note {
private def descr(elem: CoreCapability, cls: Symbol)(using Context): String =
def wrap(why: String) =
i"\n\nNote that `${elem.showAsCapability}` is a capability $why."
if cls.isStaticOwner && !cls.derivesFromCapability then
val uses = cls.useSet
if !uses.elems.isEmpty then
wrap(i"because it uses $uses")
else
val fields = cls.asClass.capturesImpliedByFields(elem).fields
if fields.nonEmpty then
val fieldsStr = fields.map(fld => i"${fld.name}: ${fld.info}").mkString(",")
val fieldsPrefix = if fields.length == 1 then "a field" else "fields"
wrap(s"because it contains $fieldsPrefix $fieldsStr")
else ""
else ""
def render(using Context) = elem.core match
case ref: TermRef => descr(ref, ref.symbol.moduleClass)
case ref: ThisType => descr(ref, ref.cls)
case _ => ""
}
/** If `res` is not CompareResult.OK, report an error */
def checkOK(res: TypeComparer.CompareResult,
added: Capability | CaptureSet,
target: CaptureSet,
targetOwner: Symbol,
provenance: => String,
pos: SrcPos)(using Context): Unit =
res match
case TypeComparer.CompareResult.Fail(notes) =>
val (includeFailures, otherNotes) = notes.partition(_.isInstanceOf[IncludeFailure])
val realTarget = includeFailures match
case (fail: IncludeFailure) :: _
if !fail.cs.isInstanceOf[CaptureSet.EmptyOfBoxed] => fail.cs
case _ => target
val whyNotes = added match
case added: Capability => WhyCapability(added) :: Nil
case added: CaptureSet => added.elems.toList.map(WhyCapability(_))
def msg = CannotBeIncluded(
added, target, realTarget, otherNotes ++ whyNotes, targetOwner, provenance)
target match
case target: CaptureSet.Var if realTarget.isProvisionallySolved =>
report.warning(
msg.prepend(i"Another capture checking run needs to be scheduled because\n"),
pos)
needAnotherRun = true
added match
case added: Capability => target.elems += added
case added: CaptureSet => target.elems ++= added.elems
case _ =>
report.error(msg, pos)
case _ =>
/** Check subcapturing `{elem} <: cs`, report error on failure */
def checkElem(elem: Capability, cs: CaptureSet, pos: SrcPos,
owner: Symbol = NoSymbol, provenance: => String = "")(using Context) =
checkOK(
TypeComparer.compareResult(elem.singletonCaptureSet.subCaptures(cs)),
elem, cs, owner, provenance, pos)
/** Check subcapturing `cs1 <: cs2`, report error on failure */
def checkSubset(cs1: CaptureSet, cs2: CaptureSet, pos: SrcPos,
owner: Symbol = NoSymbol, provenance: => String = "")(using Context) =
val cs1description = cs1.description
checkOK(
TypeComparer.compareResult(cs1.subCaptures(cs2)),
cs1, cs2, owner, provenance, pos)
// ---- Record Uses with MarkFree ----------------------------------------------------
/** The next environment enclosing `env` that needs to be charged
* with free references.
*/
def nextEnvToCharge(env: Env)(using Context): Env | Null =
if env.owner.isConstructor then env.outer.outer0
else env.outer0
/** A description where this environment comes from */
private def provenance(env: Env)(using Context): String =
var owner = env.owner
if owner.isConstructor && owner.owner.isPackageObject then
owner = owner.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 if owner.isPackageObject then
i"\nof the enclosing top-level definitions in ${owner.owner}"
else
i"\nof the enclosing ${owner.showLocated}"
/** Under deferredReaches:
* Does the given environment belong to a method that is (a) nested in a term
* and (b) not the method of an anonymous function?
*/
def isOfNestedMethod(env: Env)(using Context) =
ccConfig.deferredReaches
&& 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: Capability, tree: Tree)(using Context): Unit =
if sym.exists then markFree(ref, tree)
def markFree(ref: Capability, tree: Tree)(using Context): Unit =
if ref.isTracked then markFree(ref.singletonCaptureSet, 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, addUseInfo: Boolean = true)(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 && {
val effectiveOwner =
if env.owner.isConstructor then env.owner.owner
else env.owner
if env.kind == EnvKind.NestedInOwner then
!sym.isProperlyContainedIn(effectiveOwner)
else
!sym.isContainedIn(effectiveOwner)
}
/** Avoid locally defined capability by charging the underlying type
* (which may not be `any`). This scheme applies only under the deferredReaches setting.
*/
def avoidLocalCapability(c: Capability, env: Env, lastEnv: Env | Null): Unit =
if c.isParamPath then
c match
case Reach(_) | _: TypeRef =>
val accessFromNestedClosure =
lastEnv != null && env.nestedClosure.exists && env.nestedClosure == lastEnv.owner
if !accessFromNestedClosure then
checkUseDeclared(c, tree.srcPos)
case _ =>
else
val underlying = c match
case Reach(c1) => CaptureSet.ofTypeDeeply(c1.widen)
case _ => c.core match
case c1: RootCapability => c1.singletonCaptureSet
case c1: CoreCapability =>
CaptureSet.ofType(c1.widen, followResult = ccConfig.useSpanCapset)
capt.println(i"Widen reach $c to $underlying in ${env.owner}")
underlying.disallowBadRoots(NoSymbol): () =>
report.error(em"Local capability `${c.showAsCapability}`${env.owner.qualString("in")} cannot have `any` 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: Capability, env: Env): Unit = c match
case Reach(c1) if !c1.isParamPath =>
// Parameter reaches are rejected in checkEscapingUses.
// 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 `any`.
// 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 `any`. Reach capabilities over paths depend on the prefix, which
// might turn an `any` 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}")
recur(underlying.filter(!_.isTerminalCapability), env, null)
// We don't want to disallow underlying LocalCap instances, since these are
// typically locally created LocalCap capabilities. We do check in checkEscapingUses
// that they don't hide any parameter reach caps.
case _ =>
def checkReadOnlyMethod(included: CaptureSet, meth: Symbol): Unit =
included.checkAddedElems: elem =>
if elem.isExclusive() then
report.error(
em"""Read-only $meth accesses exclusive capability `${elem.showAsCapability}`;
|$meth should be declared an update method to allow this.""",
tree.srcPos)
def recur(cs: CaptureSet, env: Env, lastEnv: Env | Null): Unit =
if env.kind != EnvKind.Boxed && !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, env.owner, provenance(env))
capt.println(i"Include call or box capture $included from $cs in ${env.owner} --> ${env.captured}")
if !isOfNestedMethod(env) && !env.isRoot then
val nextEnv = nextEnvToCharge(env)
if nextEnv != null && !nextEnv.isRoot then
if nextEnv.owner != env.owner
&& env.owner.isReadOnlyMember
&& env.owner.owner.derivesFrom(defn.Caps_Stateful)
then
checkReadOnlyMethod(included, env.owner)
recur(included, nextEnv, env)
// Under deferredReaches, don't propagate out of methods inside terms.
// The use set of these methods will be charged when that method is called.
if !cs.isAlwaysEmpty && !CCState.discardUses then
recur(cs, curEnv, null)
if addUseInfo then useInfos += ((tree, cs, curEnv))
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: Capability): Boolean = ref.pathRoot match
case root: ThisType => ctx.owner.isContainedIn(root.cls)
case _ => true
if sym.exists && curEnv.kind != EnvKind.Boxed then
var locals = sym.useSet
if sym.isConstructor then
locals = sym.owner.asClass.mapClassCaptures(resType, locals)
markFree(locals.filter(isRetained), tree)
/** Type arguments come either from a TypeApply node or from an AppliedType
* which represents a trait parent in a template.
* - Disallow GlobalCaps and ResultCaps in such arguments.
* - 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 markFreeTypeArgs(fn: Tree, sym: Symbol, args: List[Tree])(using Context): Unit =
def isExempt = sym.isTypeTestOrCast || defn.capsErasedValueMethods.contains(sym)
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 => 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 ""
def addendum =
if arg.isInferred
then i"\nThis is often caused by a local capability$where\nleaking as part of its result."
else ""
def errTree = if !arg.isInferred && arg.span.exists then arg else fn
disallowBadRootsIn(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 markFreeTypeArgs
// ---- Check for leakages of reach capabilities ------------------------------
/** If capability `c` refers to a parameter that is not implicitly or explicitly
* @use declared, report an error.
*/
def checkUseDeclared(c: Capability, pos: SrcPos)(using Context): Unit =
c.paramPathRoot match
case ref: NamedType if !ref.symbol.isUseParam =>
val what = if ref.isType then "Capture set parameter" else "Local reach capability"
def mitigation =
if ccConfig.allowUse
then i"\nTo allow this, the ${ref.symbol} should be declared with a @use annotation."
else if !ref.isType then i"\nYou could try to abstract the capabilities referred to by $c in a capset variable."
else ""
report.error(
em"$what $c leaks into capture scope${ref.symbol.owner.qualString("of")}.$mitigation",
pos)
case _ =>
/** Warn if there is an unboxed reach capability in the result of a method
* that refers to a parameter. These uses will almost always lead to checkUseDeclared
* failures later on.
*/
def checkNoUnboxedReaches(tree: DefDef)(using Context): Unit = tree.tpt match
case tpt: TypeTree if !tpt.isInferred =>
def checkType(tp: Type) = tp match
case tp @ CapturingType(_, refs) =>
if !tp.isBoxed then
for ref <- refs.elems do
if ref.isReach then
ref.paramPathRoot match
case tp: TermRef =>
report.warning(
em"""Reach capability `${ref.showAsCapability}` in function result refers to ${tp.symbol}.
|To avoid errors of the form "Local reach capability $ref leaks into capture scope ..."
|you should replace the reach capability with a new capset variable in ${tree.symbol}.""",
tree.tpt.srcPos)
case _ =>
case _ =>
tpt.nuType.foreachPart(checkType, StopAt.Static)
case _ =>
// ---- Rechecking operations for different kinds of trees----------------------
/** If `tp` (possibly after widening singletons) is an ExprType
* of a parameterless method, map ResultCap instances in it to LocalCap instances
*/
def mapResultRoots(tp: Type, tree: Tree)(using Context): Type =
tp.widenSingleton match
case tp: ExprType if tree.symbol.is(Method) =>
resultToAny(tp, Origin.ResultInstance(tp, tree))
case _ =>
tp
/** 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.isOneOf(MethodOrLazy) then
// If ident refers to a parameterless method or lazy val, charge its cv to the environment.
// Lazy vals are like parameterless methods: accessing them may trigger initialization
// that uses captured references.
includeCallCaptures(sym, sym.info, tree)
if sym.exists && !sym.is(Package)
&& !(sym.is(Method) && ctx.owner.isContainedIn(sym.owner.skipWeakOwner))
// if it's a method in some enclosing scope the call captures already cover the use set
// skipWeakOwner: Also exempt symbols in package objects of the source when referenced
// from classes in the same source.
then
// Mark symbol as used
// - as a path if it is a member of some tracked object
// - by itself if it is not a method
tree.tpe.stripped match
case TermRef(prefix: (TermRef | ThisType), _) if prefix.isTracked =>
markPathFree(prefix, PathSelectionProto(sym, pt, tree), tree)
case _ =>
if !sym.is(Method) then
markPathFree(sym.termRef, pt, tree)
if sym.isMutableVar && sym.owner.isTerm && pt != LhsProto then
// When we have `var x: A^{c} = ...` where `x` is a local variable then
// when dereferencing `x` we also need to charge `c`.
// For fields it's not a problem since `c` would already have been
// charged for the prefix `p` in `p.x`.
markFree(sym.info.captureSet, tree)
mapResultRoots(super.recheckIdent(tree, pt), tree)
}
override def recheckThis(tree: This, pt: Type)(using Context): Type =
markPathFree(tree.tpe.asInstanceOf[ThisType], pt, tree)
super.recheckThis(tree, pt)
/** Add all selections and also any `.rd modifier implied by the expected
* type `pt` to `ref`. Expand the marked tree accordingly to take account of
* the added path. 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.rd` for tree `x.a.b`
* instead of just charging `x`.
*/
private def markPathFree(ref: TermRef | ThisType, pt: Type, tree: Tree)(using Context): Unit = pt match
case pt: PathSelectionProto
if ref.isTracked && !pt.selector.isOneOf(MethodOrLazyOrMutable) =>
// 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.
val sel = ref.select(pt.selector).asInstanceOf[TermRef]
markPathFree(sel, pt.pt, pt.tree)
case _ =>
markFree(ref.mapLocalMutable.adjustReadOnly(pt), tree)
/** 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 =
if tree.symbol.is(Package) then super.selectionProto(tree, pt)
else PathSelectionProto(tree.symbol, pt, tree)
/** 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.
if tree.symbol.isUpdateMethod then
checkUpdate(qualType, tree.srcPos):
i"Cannot call update ${tree.symbol} of ${qualType.showRef}"
val origSelType = recheckSelection(tree, qualType, name, disambiguate)
val selType = mapResultRoots(origSelType, tree)
val selWiden = selType.widen
def capturesResult = origSelType.widenSingleton match
case ExprType(resType) => resType.captureSet.containsResultCapability
case _ => false
// 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 reference or a pure type, or
// - if the selection is of a parameterless method capturing a ResultCap
if noWiden(selType, pt)
|| tree.hasAttachment(NoWiden)
|| qualType.isBoxedCapturing
|| selType.isBoxedCapturing
|| selWiden.isBoxedCapturing
|| selType.isTrackableRef
|| selWiden.captureSet.isAlwaysEmpty
|| capturesResult
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)
&& !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")
/** Recheck `caps.unsafe.unsafeAssumePure(...)` */
def applyAssumePure(tree: Apply, pt: Type)(using Context): Type =
val arg :: Nil = tree.args: @unchecked
val argType0 = recheck(arg, pt.stripCapturing.capturing(LocalCap(Origin.UnsafeAssumePure)))
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)
/** Recheck applications, with special handling of unsafeAssumePure,
* unsafeDiscardUses, and freeze.
* 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
applyAssumePure(tree, pt)
else if meth == defn.Caps_unsafeDiscardUses then
val arg :: Nil = tree.args: @unchecked
withDiscardedUses(recheck(arg, pt))
else if meth == defn.Caps_freeze then
freeze(super.recheckApply(tree, pt), tree.srcPos)
else
val res = super.recheckApply(tree, pt)
includeCallCaptures(meth, res, tree)
res
/** Recheck argument against an instantiated version of `formal` where toplevel `any`
* occurrences are replaced by LocalCap instances. Also, if formal parameter carries a `@use`
* or @consume, charge the deep capture set of the actual argument to the environment.
* TODO: Maybe not charge deep capture sets for consume?
*/
protected override def recheckArg(arg: Tree, formal: Type, pref: ParamRef, app: Apply)(using Context): Type =
val meth = app.fun.symbol
if meth.isPrimaryConstructor
&& meth.owner.asClass.refiningGetterNamed(pref.paramName).is(Tracked)
then
arg.putAttachment(NoWiden, ())
val instantiatedFormal = globalCapToLocal(formal, Origin.Formal(pref, app))
val argType = recheck(arg, instantiatedFormal)
.showing(i"recheck arg $arg vs $instantiatedFormal = $result", capt)
if formal.hasAnnotation(defn.UseAnnot) || formal.hasAnnotation(defn.ConsumeAnnot) then
// The @use and/or @consume annotation is added to `formal` when creating methods types.
// See [[MethodTypeCompanion.adaptParamInfo]].
capt.println(i"charging deep capture set of $arg: ${argType} = ${argType.deepCaptureSet}")
markFree(argType.deepCaptureSet, arg)
if formal.containsGlobalAny then
sepCheckFormals(arg) = instantiatedFormal
argType
/** Map existential captures in result to a new local `any` and implement the
* following rule:
*
* 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 instArgs =
// Improve the argument types with which the method type is instantiated.
// If the rechecked argument type is an unboxed capturing type but the previous
// argument type is a singleton type, use the previous argument type instead.
// This makes sure path dependent types in the function result are still well-formed.
// An example is i25613.scala. See i16114.scala for an example why we have to
// exclude boxed capturing types because this might lose uses stemming from unboxing
// a function result.
if argTypes.hasSameLengthAs(tree.args) then
val argTypes1 = argTypes.zipWithConserve(tree.args):
case (nuType @ CapturingType(_, _), arg: Tree)
if arg.tpe.isStable // stable --> there might be path dependent types with arg as prefix
&& arg.tpe.isTrackableRef // isTrackableRef --> we can get back original capture set by adaptation
&& !nuType.isBoxedCapturing // !isBoxed --> no risk of losing uses when unboxing in result
=> arg.tpe
case (nuType, _) => nuType
if argTypes1 ne argTypes then
capt.println(i"improve $argTypes to $argTypes1 in $tree")
argTypes1
else argTypes
val resultType = super.recheckApplication(tree, qualType, funType, instArgs)
val appType = resultToAny(resultType, Origin.ResultInstance(funType, tree))
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
&& !qualType.isBoxedCapturing
&& !resultType.isBoxedCapturing
&& !tree.fun.symbol.isConstructor
&& !resultType.captureSet.containsResultCapability
&& !resultType.captureSet.elems.exists(_.derivesFromCapTrait(defn.Caps_Unscoped))
&& 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 `refineConstructorInstance`
*/
override def instantiate(mt: MethodType, argTypes: List[Type], sym: Symbol)(using Context): Type =
val ownType =
if !mt.isResultDependent then mt.resType
else SubstParamsMap(mt, argTypes)(mt.resType)
def instCls = ownType.finalResultType.classSymbol.asClass
if sym.needsResultRefinement then
refineConstructorInstance(ownType, mt, argTypes, instCls)
else if sym.isSecondaryConstructor then
// Refine primary constructor instance with a list of arguments of matching
// length that is constructed as follows:
// - If the argument is for a primary constructor parameter named `x`
// and there is a secondary constructor parameter carrying an