How to test capture checking?

Is it possible to test capture checking programmatically, using ScalaTest or something similar?

class CCSpec extends AnyFlatSpec with Matchers {
  "Capture checking" should "fails compilation" in {
    val errors = typeCheckErrors("""
      import language.experimental.captureChecking
      import java.io.{FileInputStream, InputStream}

      def withFile[T](name: String)(op: InputStream^ => T): T =
        val f = new FileInputStream(name)
        try op(f)
        finally f.close()

      withFile("data.txt"): in =>
        in.read()
    """)
    errors shouldBe empty
  }
}
The code above fails, but the error doesn’t indicate that the resource was leaked, but the following:Capture checking
- should fails compilation *** FAILED *** (11 milliseconds)
  List(Error("this language import is only allowed at the toplevel", "      import language.experimental.captureChecking", 35, Parser)) was not empty (CCSpec.scala:74)

If we remove the import language.experimental.captureChecking from the code in the string and move it to the top of the CCSpec.scala file, it will be ignored by the compiler.

a crude idea, but maybe adding a compiler option -language like here Scala3 "-language" compiler option issues - Compiler - Scala Contributors would solve the problem? of course you would need to move tests that depend on capture checking to its own module for which you would enable that compiler option.

1 Like

Can you can pass the equivalent setting to the ScalaTest runner?

 -language:experimental.captureChecking