简体   繁体   English

使用scala meta和quasiquotes定义隐式编码器

[英]Defining implicit encoder using scala meta and quasiquotes

I am trying to create an implicit encoder using Circe. 我正在尝试使用Circe创建隐式编码器。 However this encoder will be created using an annotation hence I am using Scalameta. 但是,此编码器将使用注释创建,因此我正在使用Scalameta。 Here is my code. 这是我的代码。 However, the compiler complains about having an override statement within quasiquotes. 但是,编译器抱怨在准引用中包含覆盖声明。

class HalResource extends StaticAnnotation {
  inline def apply(defn: Any): Any = meta {
    val q"..$mods class $tName (..$params) extends $template {..$stats}" = defn

    q"object $tName {${createApply(tName)}}"
  }


  private def createApply(className: Type.Name): Defn.Def = {
    q"""
       import _root_.io.circe.Json
       import _root_.io.circe.syntax._
       import _root_.io.circe.Encoder


       implicit def encoder = Encoder[$className] {
          override def apply(a: $className): Json = {
           val (simpleFields: Seq[Term.Param], nonSimpleFields: Seq[Term.Param]) =
             params.partition(field => field.decltpe.fold(false) {
               case _: Type.Name => true
               case _ => false
             })

           val embedded: Seq[(String, Json)] = nonSimpleFields.map(field => field.name.syntax -> field.name.value.asJson)
           val simpleJsonFields: Seq[(String, Json)] = simpleFields.map(field => field.name.syntax -> field.name.value.asJson)

           val baseSeq: Seq[(String, Json)] = Seq(
             "_links" -> Json.obj(
               "href" -> Json.obj(
                 "self" -> Json.fromString("self_reference")
               )
             ),
             "_embedded" -> Json.fromFields(embedded),
           ) ++ simpleJsonFields

           val result: Seq[(String, Json)] = baseSeq ++ simpleJsonFields
           Json.fromFields(result)
          }
       }
     """
  }
}

The build file is as follows: 生成文件如下:

import sbt.Keys.{scalaVersion, scalacOptions}

val circeVersion = "0.8.0"

lazy val circeDependencies = Seq(
  "io.circe" %% "circe-core",
  "io.circe" %% "circe-generic",
  "io.circe" %% "circe-parser"
).map(_ % circeVersion)

lazy val commonSettings = Seq(
  name := "Annotation",
  version := "1.0",
  scalaVersion := "2.12.2",
  scalacOptions ++= Seq("-unchecked", "-deprecation", "-feature"),
  resolvers += Resolver.sonatypeRepo("releases")
)

lazy val macroAnnotationSettings = Seq(
  addCompilerPlugin("org.scalameta" % "paradise" % "3.0.0-M9" cross CrossVersion.full),
  scalacOptions += "-Xplugin-require:macroparadise",
  scalacOptions in (Compile, console) ~= (_ filterNot (_ contains "paradise"))
)

lazy val projectThatDefinesMacroAnnotations = project.in(file("annotation-definition"))
  .settings(commonSettings)
  .settings(
    name := "HalResource",
    libraryDependencies += "org.scalameta" %% "scalameta" % "1.8.0" % Provided,
    macroAnnotationSettings)

lazy val annotation = project.in(file("."))
  .settings(commonSettings)
  .settings(macroAnnotationSettings)
  .settings(
    libraryDependencies ++= circeDependencies
  ).dependsOn(projectThatDefinesMacroAnnotations)

As a result I still get: macro annotation could not be expanded (the most common reason for that is that you need to enable the macro paradise plugin; another possibility is that you try to use macro annotation in the same compilation run that defines it) 结果,我仍然得到: 无法扩展宏注释(最常见的原因是您需要启用宏天堂插件;另一种可能性是,您尝试在定义宏注释的同一编译运行中使用宏注释)

You are just missing new before Encoder[$className] { (there may be other errors, but that's the immediate one). 您只是在Encoder[$className] {之前错过了new ((可能还有其他错误,但这是直接的))。

Because of this, the compiler thinks you are trying to call a generic method Encoder with the block 因此,编译器认为您正在尝试使用该块调用通用方法Encoder

{
  override def apply(a: $className): Json = ...
  ...
}

as the argument, and local methods can't be override . 作为参数,并且不能override local方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM