From 050f54bbfc8492648bd0c9c61ed6c14daeb32551 Mon Sep 17 00:00:00 2001 From: Nicolas Stucki Date: Tue, 27 Jun 2023 13:46:50 +0200 Subject: [PATCH] Add regression test for #18059 Closes #18059 Probably fixed by #17342 --- tests/pos-macros/i18059/Macro_1.scala | 29 +++++++++++++++++++++++++++ tests/pos-macros/i18059/Test_2.scala | 8 ++++++++ 2 files changed, 37 insertions(+) create mode 100644 tests/pos-macros/i18059/Macro_1.scala create mode 100644 tests/pos-macros/i18059/Test_2.scala diff --git a/tests/pos-macros/i18059/Macro_1.scala b/tests/pos-macros/i18059/Macro_1.scala new file mode 100644 index 000000000000..4c3f89281883 --- /dev/null +++ b/tests/pos-macros/i18059/Macro_1.scala @@ -0,0 +1,29 @@ +import scala.annotation.StaticAnnotation + +class SqlName(val sqlName: String) extends StaticAnnotation + +import scala.compiletime.* +import scala.quoted.* + +inline def sqlFieldNamesFor[T]: Vector[(String, String)] = ${ + sqlFieldNamesForImpl[T] +} + +private def sqlFieldNamesForImpl[T: Type](using + Quotes // must be named!! like `q: Quotes` +): Expr[Vector[(String, String)]] = + import quotes.reflect.* + val annot = TypeRepr.of[SqlName].typeSymbol + val tuples: Seq[Expr[(String, String)]] = TypeRepr + .of[T] + .typeSymbol + .primaryConstructor + .paramSymss + .head + .collect: + case sym if sym.hasAnnotation(annot) => + val fieldNameExpr = Expr(sym.name.asInstanceOf[String]) + val annotExpr = sym.getAnnotation(annot).get.asExprOf[SqlName] + '{ ($fieldNameExpr, $annotExpr.sqlName) } + val seq: Expr[Seq[(String, String)]] = Expr.ofSeq(tuples) + '{ $seq.toVector } diff --git a/tests/pos-macros/i18059/Test_2.scala b/tests/pos-macros/i18059/Test_2.scala new file mode 100644 index 000000000000..223cf626be87 --- /dev/null +++ b/tests/pos-macros/i18059/Test_2.scala @@ -0,0 +1,8 @@ +case class AppUser( + id: Long, + firstName: Option[String], + @SqlName("last_name") lastName: String +) + +def hello: Unit = + println(sqlFieldNamesFor[AppUser]) // Vector((lastName, last_name))