#!/bin/sh
# Staging test: generate, compile and run code at run time with
# scala.quoted.staging, which needs the compiler jars at run time.
set -e

WORK="${AUTOPKGTEST_TMP:-$(mktemp -d)}"
cd "$WORK"

cat > Staged.scala <<'X'
import scala.quoted.*
import scala.quoted.staging.*

given Compiler = Compiler.make(ClassLoader.getSystemClassLoader)

def powerCode(x: Expr[Int], n: Int)(using Quotes): Expr[Int] =
  if n == 0 then '{ 1 } else '{ $x * ${ powerCode(x, n - 1) } }

@main def staged(): Unit =
  val power3: Int => Int = run { '{ (x: Int) => ${ powerCode('x, 3) } } }
  println(s"power3(4) = ${power3(4)}")
X

J=/usr/share/java
CP=$J/scala3-staging-3.jar:$J/scala3-compiler-3.jar:$J/scala3-interfaces-3.jar:$J/tasty-core-3.jar
CP=$CP:/usr/share/maven-repo/org/scala-lang/modules/scala-asm/debian/scala-asm-debian.jar
CP=$CP:$J/sbt-compiler-interface.jar:$J/sbt-util-interface.jar
mkdir out
scalac-3 -d out -classpath "$CP" Staged.scala
scala-3 -cp "out:$CP" staged > got.txt
cat got.txt
grep -qx 'power3(4) = 64' got.txt
echo "staging test: PASS"
