Implement a Scala macro that performs compile-time code validation.
Instruction: Provide an example of a Scala macro that validates code at compile time, explaining its implementation and use-case.
Updated
Validate a property that is actually knowable at compilation. This Scala 3 macro accepts a constant integer port in the inclusive range 1 through 65535. It rejects both invalid constants and values unavailable to the macro at compile time.
Define PortLiteral.scala:
import scala.quoted.*
object PortLiteral {
inline def apply(inline value: Int): Int = ${ validate('value) }
private def validate(value: Expr[Int])(using Quotes): Expr[Int] = {
value.value match {
case Some(n) if n >= 1 && n <= 65535 => Expr(n)
case Some(_) =>
quotes.reflect.report.errorAndAbort("Port must be in 1..65535")
case None =>
quotes.reflect.report.errorAndAbort("Port must be a constant Int")
}
}
}
Use it in another file, UsePort.scala:
@main def portLiteralExample(): Unit = {
val port = PortLiteral(8080)
assert(port == 8080)
assert(PortLiteral(1) == 1 && PortLiteral(65535) == 65535)
}
Compile the two source files with Scala 3. The splice runs the validator during compilation; successful expansion inserts the validated integer. PortLiteral(0) and PortLiteral(65536) produce the range diagnostic. A method parameter passed to PortLiteral produces the constant-value diagnostic. The use site must be in a different source file from the macro definition. Scala 3 macros
This checks only the stated literal range. It does not prove that a port is available, permitted or reachable, and returning an Int does not prevent other APIs from accepting unvalidated integers. A value read from configuration needs a runtime validator, usually returning a structured error.
Searching a syntax tree for a try expression would not establish correct exception handling: the catch might handle the wrong exception, ignore it, or not cover the relevant operation. Prefer explicit, narrow macro contracts, useful diagnostics and positive/negative compilation tests over claiming a general proof of application safety.