diff --git a/.scalafmt.conf b/.scalafmt.conf index ec12fb754ab710f37c71e28568833692a87eb057..f098599e69485b976e8399cd1b4119b651b40168 100644 --- a/.scalafmt.conf +++ b/.scalafmt.conf @@ -1,19 +1,21 @@ -version = "2.7.5" +version = "3.5.3" +runner.dialect = scala213 maxColumn = 120 -align = most -continuationIndent.defnSite = 2 -assumeStandardLibraryStripMargin = true -docstrings = JavaDoc +align.preset = more lineEndings = preserve -includeCurlyBraceInSelectChains = false -danglingParentheses = true +align.stripMargin = false +docstrings.style = AsteriskSpace +docstrings.oneline = keep +continuationIndent.defnSite = 2 +danglingParentheses.preset = true spaces { inImportCurlyBraces = true } +indentOperator.exemptScope = aloneArgOrBody +includeCurlyBraceInSelectChains = false +align.openParenDefnSite = false optIn.annotationNewlines = true - rewrite.rules = [SortImports, RedundantBraces] -align.openParenDefnSite = false rewriteTokens = { "⇒": "=>" "→": "->" diff --git a/build.sbt b/build.sbt index 08a7316ddf42bd2c8617e3086f5bc6acece43122..85af3c3a69375a770f4ada119a43823f37b4a7ad 100644 --- a/build.sbt +++ b/build.sbt @@ -8,35 +8,35 @@ ThisBuild / resolvers ++= Seq( "New snapshots" at "https://s01.oss.sonatype.org/content/repositories/snapshots/" ) -lazy val scala212 = "2.12.14" -lazy val scala211 = "2.11.12" -lazy val scala213 = "2.13.8" +lazy val scala212 = "2.12.14" +lazy val scala211 = "2.11.12" +lazy val scala213 = "2.13.8" lazy val lastVersionForExamples = "0.5.2" -lazy val scalatestVersion = "3.2.12" -lazy val zioVersion = "1.0.14" -lazy val zioLoggingVersion = "0.5.14" -lazy val configVersion = "1.4.2" -lazy val caffeineVersion = "2.9.3" -lazy val zioRedisVersion = "0.0.0+381-86c20614-SNAPSHOT" // 实验性质的 -lazy val zioSchemaVersion = "0.1.9" +lazy val scalatestVersion = "3.2.12" +lazy val zioVersion = "1.0.14" +lazy val zioLoggingVersion = "0.5.14" +lazy val configVersion = "1.4.2" +lazy val caffeineVersion = "2.9.3" +lazy val zioRedisVersion = "0.0.0+381-86c20614-SNAPSHOT" // 实验性质的 +lazy val zioSchemaVersion = "0.1.9" lazy val scalaLoggingVersion = "3.9.4" -lazy val playJsonVersion = "2.7.4" -lazy val log4jVersion = "2.17.2" +lazy val playJsonVersion = "2.7.4" +lazy val log4jVersion = "2.17.2" lazy val jacksonScalaVersion = "2.13.2" -lazy val jraftVersion = "1.3.9" -lazy val protocVersion = "3.20.1" +lazy val jraftVersion = "1.3.9" +lazy val protocVersion = "3.20.1" lazy val commonSettings = Seq( - organization := "org.bitlap", + organization := "org.bitlap", organizationName := "bitlap", - startYear := Some(2022), - scalaVersion := scala213, + startYear := Some(2022), + scalaVersion := scala213, libraryDependencies ++= Seq( "org.scala-lang" % "scala-compiler" % scalaVersion.value, - "org.scala-lang" % "scala-reflect" % scalaVersion.value, - "org.scalatest" %% "scalatest" % scalatestVersion % Test + "org.scala-lang" % "scala-reflect" % scalaVersion.value, + "org.scalatest" %% "scalatest" % scalatestVersion % Test ), Compile / scalacOptions ++= { CrossVersion.partialVersion(scalaVersion.value) match { @@ -44,12 +44,12 @@ lazy val commonSettings = case _ => List("-Ymacro-annotations", "-Ywarn-unused" /*, "-Ymacro-debug-verbose"*/ ) } } ++ Seq("-language:experimental.macros"), - Compile / compile := (Compile / compile).dependsOn(Compile / headerCreateAll).value, + Compile / compile := (Compile / compile).dependsOn(Compile / headerCreateAll).value, Global / onChangedBuildSource := ReloadOnSourceChanges, - headerLicense := Some(HeaderLicense.MIT("2022", "bitlap")), + headerLicense := Some(HeaderLicense.MIT("2022", "bitlap")), Test / testOptions += Tests.Argument("-oDF"), - Test / fork := true, - publishConfiguration := publishConfiguration.value.withOverwrite(true), + Test / fork := true, + publishConfiguration := publishConfiguration.value.withOverwrite(true), publishLocalConfiguration := publishLocalConfiguration.value.withOverwrite(true) ) @@ -57,10 +57,10 @@ lazy val `smt-cacheable-core` = (project in file("smt-cacheable-core")) .settings(commonSettings) .settings(Publishing.publishSettings) .settings( - name := "smt-cacheable-core", + name := "smt-cacheable-core", crossScalaVersions := List(scala213, scala212), libraryDependencies ++= Seq( - "dev.zio" %% "zio" % zioVersion, // FIXME we should use compile or provide ??? + "dev.zio" %% "zio" % zioVersion, // FIXME we should use compile or provide ??? "dev.zio" %% "zio-streams" % zioVersion, "dev.zio" %% "zio-logging" % zioLoggingVersion ) @@ -72,10 +72,10 @@ lazy val `smt-cacheable-caffeine` = (project in file("smt-cacheable-caffeine")) .settings(commonSettings) .settings(Publishing.publishSettings) .settings( - name := "smt-cacheable-caffeine", + name := "smt-cacheable-caffeine", crossScalaVersions := List(scala213, scala212), libraryDependencies ++= Seq( - "com.typesafe" % "config" % configVersion, + "com.typesafe" % "config" % configVersion, "com.github.ben-manes.caffeine" % "caffeine" % caffeineVersion ) ) @@ -87,14 +87,14 @@ lazy val `smt-cacheable-redis` = (project in file("smt-cacheable-redis")) .settings(commonSettings) .settings(Publishing.publishSettings) .settings( - name := "smt-cacheable-redis", + name := "smt-cacheable-redis", crossScalaVersions := List(scala213, scala212), libraryDependencies ++= Seq( - "dev.zio" %% "zio-redis" % zioRedisVersion, - "com.typesafe" % "config" % configVersion, - "dev.zio" %% "zio-schema" % zioSchemaVersion, - "dev.zio" %% "zio-schema-json" % zioSchemaVersion, - "dev.zio" %% "zio-schema-derivation" % zioSchemaVersion % Test + "dev.zio" %% "zio-redis" % zioRedisVersion, + "com.typesafe" % "config" % configVersion, + "dev.zio" %% "zio-schema" % zioSchemaVersion, + "dev.zio" %% "zio-schema-json" % zioSchemaVersion, + "dev.zio" %% "zio-schema-derivation" % zioSchemaVersion % Test ) ) .dependsOn(`smt-cacheable-core` % "compile->compile;test->test") @@ -104,7 +104,7 @@ lazy val `smt-cacheable-redis` = (project in file("smt-cacheable-redis")) lazy val `smt-benchmark` = (project in file("smt-benchmark")) .settings(commonSettings) .settings( - name := "smt-benchmark", + name := "smt-benchmark", publish / skip := true ) .dependsOn(`smt-cacheable-core`, `smt-cacheable-redis`, `smt-cacheable-caffeine`) @@ -114,7 +114,7 @@ lazy val `smt-benchmark` = (project in file("smt-benchmark")) lazy val `smt-csv-core` = (project in file("smt-csv-core")) .settings(commonSettings) .settings( - name := "smt-csv-core", + name := "smt-csv-core", crossScalaVersions := List(scala213, scala212, scala211) ) .settings(Publishing.publishSettings) @@ -124,7 +124,7 @@ lazy val `smt-csv-core` = (project in file("smt-csv-core")) lazy val `smt-csv-derive` = (project in file("smt-csv-derive")) .settings(commonSettings) .settings( - name := "smt-csv-derive", + name := "smt-csv-derive", crossScalaVersions := List(scala213, scala212, scala211) ) .settings(Publishing.publishSettings) @@ -135,17 +135,17 @@ lazy val `smt-csv-derive` = (project in file("smt-csv-derive")) lazy val `smt-tools` = (project in file("smt-tools")) .settings(commonSettings) .settings( - name := "smt-tools", + name := "smt-tools", crossScalaVersions := List(scala213, scala212, scala211), libraryDependencies ++= Seq( - "com.typesafe.scala-logging" %% "scala-logging" % scalaLoggingVersion, - "com.typesafe.play" %% "play-json" % playJsonVersion % Test, - "org.apache.logging.log4j" % "log4j-api" % log4jVersion % Test, - "org.apache.logging.log4j" % "log4j-core" % log4jVersion % Test, - "org.apache.logging.log4j" % "log4j-slf4j-impl" % log4jVersion % Test, + "com.typesafe.scala-logging" %% "scala-logging" % scalaLoggingVersion, + "com.typesafe.play" %% "play-json" % playJsonVersion % Test, + "org.apache.logging.log4j" % "log4j-api" % log4jVersion % Test, + "org.apache.logging.log4j" % "log4j-core" % log4jVersion % Test, + "org.apache.logging.log4j" % "log4j-slf4j-impl" % log4jVersion % Test, "com.fasterxml.jackson.module" %% "jackson-module-scala" % jacksonScalaVersion % Test, - "com.alipay.sofa" % "jraft-core" % jraftVersion % Test, - "com.google.protobuf" % "protobuf-java" % protocVersion % Test + "com.alipay.sofa" % "jraft-core" % jraftVersion % Test, + "com.google.protobuf" % "protobuf-java" % protocVersion % Test ) ) .settings(Publishing.publishSettings) @@ -164,12 +164,12 @@ lazy val root = (project in file(".")) ) .settings( commands ++= Commands.value, - crossScalaVersions := Nil, - publish / skip := true, - headerLicense := Some(HeaderLicense.MIT("2022", "bitlap")), - releaseIgnoreUntrackedFiles := true, - releaseCrossBuild := false, //@see https://www.scala-sbt.org/1.x/docs/Cross-Build.html - releaseTagName := (ThisBuild / version).value, + crossScalaVersions := Nil, + publish / skip := true, + headerLicense := Some(HeaderLicense.MIT("2022", "bitlap")), + releaseIgnoreUntrackedFiles := true, + releaseCrossBuild := false, // @see https://www.scala-sbt.org/1.x/docs/Cross-Build.html + releaseTagName := (ThisBuild / version).value, releasePublishArtifactsAction := PgpKeys.publishSigned.value, releaseProcess := Seq[ReleaseStep]( checkSnapshotDependencies, @@ -192,9 +192,9 @@ lazy val `scala2-13` = (project in file("examples/scala2-13")) .settings(scalaVersion := scala213) .settings( libraryDependencies ++= Seq( - "org.bitlap" %% "smt-tools" % lastVersionForExamples, - "org.bitlap" %% "smt-cacheable-core" % lastVersionForExamples, - "org.bitlap" %% "smt-cacheable-redis" % lastVersionForExamples, + "org.bitlap" %% "smt-tools" % lastVersionForExamples, + "org.bitlap" %% "smt-cacheable-core" % lastVersionForExamples, + "org.bitlap" %% "smt-cacheable-redis" % lastVersionForExamples, "org.bitlap" %% "smt-cacheable-caffeine" % lastVersionForExamples ) ) @@ -207,9 +207,9 @@ lazy val `scala2-12` = (project in file("examples/scala2-12")) .settings(scalaVersion := scala212) .settings( libraryDependencies ++= Seq( - "org.bitlap" %% "smt-tools" % lastVersionForExamples, - "org.bitlap" %% "smt-cacheable-core" % lastVersionForExamples, - "org.bitlap" %% "smt-cacheable-redis" % lastVersionForExamples, + "org.bitlap" %% "smt-tools" % lastVersionForExamples, + "org.bitlap" %% "smt-cacheable-core" % lastVersionForExamples, + "org.bitlap" %% "smt-cacheable-redis" % lastVersionForExamples, "org.bitlap" %% "smt-cacheable-caffeine" % lastVersionForExamples ) ) diff --git a/project/Commands.scala b/project/Commands.scala index 38dafcdf65b44ab6b6ffa26323c80697cac41a87..4db74add8f8c0f7af3b8671d226df41e73093132 100644 --- a/project/Commands.scala +++ b/project/Commands.scala @@ -1,9 +1,9 @@ import sbt.Command -/** - * @author 梦境迷离 - * @since 2022/1/15 - * @version 1.0 +/** @author + * 梦境迷离 + * @since 2022/1/15 + * @version 1.0 */ object Commands { diff --git a/project/Publishing.scala b/project/Publishing.scala index 7dd7006b221ff536e3a6a9572655971f6f0e8040..1e13d4cb2cbd22dde02e55f0559bf537bb77ede1 100644 --- a/project/Publishing.scala +++ b/project/Publishing.scala @@ -2,16 +2,16 @@ import sbt.Keys._ import sbt._ import xerial.sbt.Sonatype.autoImport._ -/** - * sbt publish setting +/** sbt publish setting * - * @author 梦境迷离 dreamylost - * @since 2020-07-19 - * @version v1.0 + * @author + * 梦境迷离 dreamylost + * @since 2020-07-19 + * @version v1.0 */ object Publishing { - //publish by sbt publishSigned + // publish by sbt publishSigned lazy val publishSettings = Seq( isSnapshot := version.value endsWith "SNAPSHOT", credentials += Credentials(Path.userHome / ".ivy2" / ".bitlap_sonatype_credentials"), @@ -22,10 +22,10 @@ object Publishing { else Some("releases" at nexus + "service/local/staging/deploy/maven2") }, - licenses := Seq(License.MIT), - publishMavenStyle := true, + licenses := Seq(License.MIT), + publishMavenStyle := true, Test / publishArtifact := false, - pomIncludeRepository := { _ => false }, + pomIncludeRepository := { _ => false }, developers := List( Developer( id = "dreamylost", @@ -41,7 +41,7 @@ object Publishing { ) ), sonatypeProfileName := organization.value, - homepage := Some(url("https://bitlap.org")), + homepage := Some(url("https://bitlap.org")), scmInfo := Some( ScmInfo( url("https://github.com/bitlap/scala-macro-tools"), diff --git a/project/plugins.sbt b/project/plugins.sbt index 901a9f0dadde43c98f4c073c18dc87c0ed6014ec..ff056bfb86fe133a381ffd4012723cb2e54129a7 100644 --- a/project/plugins.sbt +++ b/project/plugins.sbt @@ -1,8 +1,8 @@ -addSbtPlugin("org.xerial.sbt" % "sbt-sonatype" % "3.9.12") -addSbtPlugin("com.github.sbt" % "sbt-pgp" % "2.1.2") -addSbtPlugin("com.github.gseitz" % "sbt-release" % "1.0.13") -addSbtPlugin("de.heikoseeberger" % "sbt-header" % "5.7.0") -addSbtPlugin("org.scoverage" % "sbt-scoverage" % "1.9.3") -addSbtPlugin("pl.project13.scala" % "sbt-jmh" % "0.4.3") -addSbtPlugin("org.scalameta" % "sbt-scalafmt" % "2.4.6") -addSbtPlugin("ch.epfl.scala" % "sbt-scalafix" % "0.10.0") +addSbtPlugin("org.xerial.sbt" % "sbt-sonatype" % "3.9.12") +addSbtPlugin("com.github.sbt" % "sbt-pgp" % "2.1.2") +addSbtPlugin("com.github.gseitz" % "sbt-release" % "1.0.13") +addSbtPlugin("de.heikoseeberger" % "sbt-header" % "5.7.0") +addSbtPlugin("org.scoverage" % "sbt-scoverage" % "1.9.3") +addSbtPlugin("pl.project13.scala" % "sbt-jmh" % "0.4.3") +addSbtPlugin("org.scalameta" % "sbt-scalafmt" % "2.4.6") +addSbtPlugin("ch.epfl.scala" % "sbt-scalafix" % "0.10.0") diff --git a/smt-benchmark/src/main/scala/org/bitlap/cacheable/benchmark/BenchmarkRuntime.scala b/smt-benchmark/src/main/scala/org/bitlap/cacheable/benchmark/BenchmarkRuntime.scala index 3bf8bd4a7c663244e23276dcbae84bc2e8dd59ef..32d86510f12b54130387cf47d558d18f1f6b4d7d 100644 --- a/smt-benchmark/src/main/scala/org/bitlap/cacheable/benchmark/BenchmarkRuntime.scala +++ b/smt-benchmark/src/main/scala/org/bitlap/cacheable/benchmark/BenchmarkRuntime.scala @@ -24,11 +24,11 @@ package org.bitlap.cacheable.benchmark import zio.{ BootstrapRuntime, ZIO } import zio.internal.Platform -/** - * runtime +/** runtime * - * @author 梦境迷离 - * @version 1.0,2022/3/22 + * @author + * 梦境迷离 + * @version 1.0,2022/3/22 */ trait BenchmarkRuntime extends BootstrapRuntime { diff --git a/smt-benchmark/src/main/scala/org/bitlap/cacheable/benchmark/CacheableBenchmarks.scala b/smt-benchmark/src/main/scala/org/bitlap/cacheable/benchmark/CacheableBenchmarks.scala index 7a9da17c2ec08137458af25c9af0bf7046f9be28..6c97231aef8e963a4f12bac30fd96603a744953a 100644 --- a/smt-benchmark/src/main/scala/org/bitlap/cacheable/benchmark/CacheableBenchmarks.scala +++ b/smt-benchmark/src/main/scala/org/bitlap/cacheable/benchmark/CacheableBenchmarks.scala @@ -30,11 +30,11 @@ import zio.ZIO import java.util.concurrent.TimeUnit import scala.util.Random -/** - * benchmark @cacheable +/** benchmark @cacheable * - * @author 梦境迷离 - * @version 1.0,2022/3/22 + * @author + * 梦境迷离 + * @version 1.0,2022/3/22 */ @State(Scope.Thread) @BenchmarkMode(Array(Mode.Throughput)) diff --git a/smt-cacheable-caffeine/src/main/scala/org/bitlap/cacheable/caffeine/Implicits.scala b/smt-cacheable-caffeine/src/main/scala/org/bitlap/cacheable/caffeine/Implicits.scala index a3a91778675dd5793b72e9657ab792747e0fffc3..73a236bd418a29c74bb202d44d7e138c4fd35d9d 100644 --- a/smt-cacheable-caffeine/src/main/scala/org/bitlap/cacheable/caffeine/Implicits.scala +++ b/smt-cacheable-caffeine/src/main/scala/org/bitlap/cacheable/caffeine/Implicits.scala @@ -28,11 +28,11 @@ import org.bitlap.cacheable.core._ import zio.ZIO import zio.stream.ZStream -/** - * redis cache +/** redis cache * - * @author 梦境迷离 - * @version 1.0,2022/3/21 + * @author + * 梦境迷离 + * @version 1.0,2022/3/21 */ object Implicits { @@ -53,10 +53,10 @@ object Implicits { override def getIfPresent( business: => ZStream[Any, Throwable, T] )(identities: List[String], args: List[_]): ZStream[Any, Throwable, T] = { - val key = cacheKey(identities) - val field = cacheField(args) + val key = cacheKey(identities) + val field = cacheField(args) val syncResultFuture = zio.Runtime.global.unsafeRunToFuture(business.runCollect) - lazy val result = Await.result(syncResultFuture, ZCaffeine.calculateResultTimeout) + lazy val result = Await.result(syncResultFuture, ZCaffeine.calculateResultTimeout) for { chunk <- ZStream.fromEffect( ZCaffeine @@ -95,7 +95,7 @@ object Implicits { override def getIfPresent( business: => ZIO[Any, Throwable, T] )(identities: List[String], args: List[_]): ZIO[Any, Throwable, T] = { - val key = cacheKey(identities) + val key = cacheKey(identities) val field = cacheField(args) for { cacheValue <- ZCaffeine.hGet[T](key, field) diff --git a/smt-cacheable-caffeine/src/main/scala/org/bitlap/cacheable/caffeine/ZCaffeine.scala b/smt-cacheable-caffeine/src/main/scala/org/bitlap/cacheable/caffeine/ZCaffeine.scala index db3b77a641930eac2e1b592ce4ef07b19478d28d..09e7f20b13264b05b7adbf2c5b78f4818c2e4fce 100644 --- a/smt-cacheable-caffeine/src/main/scala/org/bitlap/cacheable/caffeine/ZCaffeine.scala +++ b/smt-cacheable-caffeine/src/main/scala/org/bitlap/cacheable/caffeine/ZCaffeine.scala @@ -28,15 +28,15 @@ import org.bitlap.cacheable.core.Utils import java.util.concurrent.{ ConcurrentHashMap, TimeUnit } import scala.concurrent.duration.Duration -/** - * @author 梦境迷离 - * @version 1.0,2022/3/21 +/** @author + * 梦境迷离 + * @version 1.0,2022/3/21 */ object ZCaffeine { import zio.Task - private val conf: Config = ConfigFactory.load("reference.conf") + private val conf: Config = ConfigFactory.load("reference.conf") private val custom: Config = ConfigFactory.load("application.conf").withFallback(conf) private[caffeine] lazy val disabledLog: Boolean = custom.getBoolean("caffeine.disabledLog") @@ -44,7 +44,7 @@ object ZCaffeine { custom.getString("caffeine.calculateResultTimeout") ) - private lazy val maximumSize: Int = custom.getInt("caffeine.maximumSize") + private lazy val maximumSize: Int = custom.getInt("caffeine.maximumSize") private lazy val expireAfterWriteSeconds: Int = custom.getInt("caffeine.expireAfterWriteSeconds") val hashCache: Cache[String, ConcurrentHashMap[String, Any]] = Caffeine diff --git a/smt-cacheable-caffeine/src/test/scala/org/bitlap/cacheable/caffeine/CacheEvictTest.scala b/smt-cacheable-caffeine/src/test/scala/org/bitlap/cacheable/caffeine/CacheEvictTest.scala index 403e2c6ace9cd1f9e1830c2117933877af5a6df7..eaaa375998c862bcfa44305567e6753a31174fd7 100644 --- a/smt-cacheable-caffeine/src/test/scala/org/bitlap/cacheable/caffeine/CacheEvictTest.scala +++ b/smt-cacheable-caffeine/src/test/scala/org/bitlap/cacheable/caffeine/CacheEvictTest.scala @@ -29,10 +29,10 @@ import zio.stream.ZStream import scala.util.Random -/** - * @author 梦境迷离 - * @since 2022/3/19 - * @version 1.0 +/** @author + * 梦境迷离 + * @since 2022/3/19 + * @version 1.0 */ class CacheEvictTest extends AnyFlatSpec with Matchers { @@ -45,7 +45,7 @@ class CacheEvictTest extends AnyFlatSpec with Matchers { def readIOFunction: String = "hello world" - val readIOMethodName = "readIOFunction" + val readIOMethodName = "readIOFunction" val readStreamMethodName = "readStreamFunction" "cacheEvict1" should "expected annotation pattern" in { @@ -93,10 +93,10 @@ class CacheEvictTest extends AnyFlatSpec with Matchers { ZIO.effect(Random.nextInt() + "") val result = runtime.unsafeRun(for { - _ <- ZCaffeine.del("CacheableTest-" + readIOMethodName) - read <- readIOFunction(1, "hello") + _ <- ZCaffeine.del("CacheableTest-" + readIOMethodName) + read <- readIOFunction(1, "hello") update <- updateIOFunction(1, "hello") - cache <- ZCaffeine.hGet[String]("CacheableTest-" + readIOMethodName, "1-hello") + cache <- ZCaffeine.hGet[String]("CacheableTest-" + readIOMethodName, "1-hello") } yield cache) result shouldEqual None } @@ -113,10 +113,10 @@ class CacheEvictTest extends AnyFlatSpec with Matchers { ZStream.fromEffect(ZIO.effect(Random.nextInt() + "")) val result = runtime.unsafeRun(for { - _ <- ZCaffeine.del("CacheableTest-" + readStreamMethodName) - read <- readStreamFunction(1, "hello").runHead + _ <- ZCaffeine.del("CacheableTest-" + readStreamMethodName) + read <- readStreamFunction(1, "hello").runHead update <- updateStreamFunction(1, "hello").runHead - cache <- ZCaffeine.hGet[String]("CacheableTest-" + readStreamMethodName, "1-hello") + cache <- ZCaffeine.hGet[String]("CacheableTest-" + readStreamMethodName, "1-hello") } yield cache) result shouldEqual None } diff --git a/smt-cacheable-caffeine/src/test/scala/org/bitlap/cacheable/caffeine/CacheableTest.scala b/smt-cacheable-caffeine/src/test/scala/org/bitlap/cacheable/caffeine/CacheableTest.scala index cdb32e42cda63888a8c0763300871143b4b668fd..4832acafb364a050cef09bdc0a470cd76b092615 100644 --- a/smt-cacheable-caffeine/src/test/scala/org/bitlap/cacheable/caffeine/CacheableTest.scala +++ b/smt-cacheable-caffeine/src/test/scala/org/bitlap/cacheable/caffeine/CacheableTest.scala @@ -30,10 +30,10 @@ import zio.{ Chunk, Task, ZIO } import java.util import scala.util.Random -/** - * @author 梦境迷离 - * @since 2021/8/7 - * @version 1.0 +/** @author + * 梦境迷离 + * @since 2021/8/7 + * @version 1.0 */ class CacheableTest extends AnyFlatSpec with Matchers { @@ -89,9 +89,9 @@ class CacheableTest extends AnyFlatSpec with Matchers { ZIO.effect(cacheValue) val result = runtime.unsafeRun(for { - _ <- ZCaffeine.del("CacheableTest-readIOFunction") + _ <- ZCaffeine.del("CacheableTest-readIOFunction") method <- readIOFunction(1, "hello") - cache <- ZCaffeine.hGet[String]("CacheableTest-readIOFunction", "1-hello") + cache <- ZCaffeine.hGet[String]("CacheableTest-readIOFunction", "1-hello") } yield method -> cache) Some(result._1) shouldEqual result._2 } @@ -119,10 +119,10 @@ class CacheableTest extends AnyFlatSpec with Matchers { ) val result = runtime.unsafeRun(for { - _ <- ZCaffeine.del("CacheableTest-readIOFunction") + _ <- ZCaffeine.del("CacheableTest-readIOFunction") method <- readIOFunction(globalId.toInt).runHead update <- updateIOFunction("lisi").runHead - after <- readIOFunction(globalId.toInt).runHead + after <- readIOFunction(globalId.toInt).runHead } yield Some("lisi") -> after.map(_.name)) result._1 shouldEqual result._2 } @@ -142,10 +142,10 @@ class CacheableTest extends AnyFlatSpec with Matchers { val newId = Random.nextInt().toString val result = runtime.unsafeRun(for { - _ <- ZCaffeine.del("CacheableTest-readIOFunction") + _ <- ZCaffeine.del("CacheableTest-readIOFunction") method <- readIOFunction(globalId.toInt).runHead update <- updateIOFunction(newId).runHead - after <- readIOFunction(globalId.toInt).runHead + after <- readIOFunction(globalId.toInt).runHead } yield Some(newId) -> after.map(_.id)) result._1 shouldEqual result._2 } @@ -159,9 +159,9 @@ class CacheableTest extends AnyFlatSpec with Matchers { println(chunk) val result = runtime.unsafeRun(for { - _ <- ZCaffeine.del("CacheableTest-readIOFunction") + _ <- ZCaffeine.del("CacheableTest-readIOFunction") method <- readIOFunction(1, "hello") - cache <- ZCaffeine.hGet[Chunk[String]]("CacheableTest-readIOFunction", "1-hello").map(_.getOrElse(Chunk.empty)) + cache <- ZCaffeine.hGet[Chunk[String]]("CacheableTest-readIOFunction", "1-hello").map(_.getOrElse(Chunk.empty)) } yield method -> cache) result._1 shouldEqual result._2 } diff --git a/smt-cacheable-caffeine/src/test/scala/org/bitlap/cacheable/caffeine/CustomCacheableTest.scala b/smt-cacheable-caffeine/src/test/scala/org/bitlap/cacheable/caffeine/CustomCacheableTest.scala index 47b9bb954fcd823d398f79fc7e2ed186dd95f198..214ee5f894e7f889b9eb54f2f52aafed7d75a367 100644 --- a/smt-cacheable-caffeine/src/test/scala/org/bitlap/cacheable/caffeine/CustomCacheableTest.scala +++ b/smt-cacheable-caffeine/src/test/scala/org/bitlap/cacheable/caffeine/CustomCacheableTest.scala @@ -28,10 +28,10 @@ import zio.ZIO import scala.util.Random -/** - * @author 梦境迷离 - * @since 2022/3/20 - * @version 1.0 +/** @author + * 梦境迷离 + * @since 2022/3/20 + * @version 1.0 */ class CustomCacheableTest extends AnyFlatSpec with Matchers { diff --git a/smt-cacheable-core/src/main/scala/org/bitlap/cacheable/core/Cache.scala b/smt-cacheable-core/src/main/scala/org/bitlap/cacheable/core/Cache.scala index 344097dc419acd00bd9637e10f817bdb691cedc4..fcb1567561ea3e387c01cb5fa2ea14c68133daa8 100644 --- a/smt-cacheable-core/src/main/scala/org/bitlap/cacheable/core/Cache.scala +++ b/smt-cacheable-core/src/main/scala/org/bitlap/cacheable/core/Cache.scala @@ -24,45 +24,52 @@ package org.bitlap.cacheable.core import zio.ZIO import zio.stream.ZStream -/** - * A distributed cache for zio. +/** A distributed cache for zio. * - * @tparam Z The result type of the function that returns the ZIO or ZStream effect. + * @tparam Z + * The result type of the function that returns the ZIO or ZStream effect. */ trait Cache[Z] { - /** - * Get cache or getAndSet cache from Cache while read data. + /** Get cache or getAndSet cache from Cache while read data. * - * @param business The function that returns the ZIO or ZStream effect. - * @param identities Append all strings for cache key. - * @param args The parameters of the business function. - * @return The result fo the business function. + * @param business + * The function that returns the ZIO or ZStream effect. + * @param identities + * Append all strings for cache key. + * @param args + * The parameters of the business function. + * @return + * The result fo the business function. */ def getIfPresent(business: => Z)(identities: List[String], args: List[_]): Z - /** - * Evict cache while data update. + /** Evict cache while data update. * - * @param business The function that returns the ZIO or ZStream effect. - * @param identities Append all strings for cache key. - * @return The result fo the business function. + * @param business + * The function that returns the ZIO or ZStream effect. + * @param identities + * Append all strings for cache key. + * @return + * The result fo the business function. */ def evict(business: => Z)(identities: List[String]): Z - /** - * Build a string for cache key. + /** Build a string for cache key. * - * @param keys Append all strings for hash key - * @return string + * @param keys + * Append all strings for hash key + * @return + * string */ def cacheKey(keys: List[String]): String = keys.mkString("-") - /** - * Build a string for cache field. + /** Build a string for cache field. * - * @param args The parameters of the business function. - * @return hash field + * @param args + * The parameters of the business function. + * @return + * hash field */ def cacheField(args: List[_]): String = args.map(_.toString).mkString("-") diff --git a/smt-cacheable-core/src/main/scala/org/bitlap/cacheable/core/Utils.scala b/smt-cacheable-core/src/main/scala/org/bitlap/cacheable/core/Utils.scala index b10c2252488bfec9ea4f79eb4d02143e414a88c8..608b4a525d74324379eb2d4a48480163886c8b70 100644 --- a/smt-cacheable-core/src/main/scala/org/bitlap/cacheable/core/Utils.scala +++ b/smt-cacheable-core/src/main/scala/org/bitlap/cacheable/core/Utils.scala @@ -28,11 +28,11 @@ import zio.stream.{ UStream, ZStream } import zio.{ UIO, ULayer, URLayer, ZIO } import zio.blocking.Blocking -/** - * Internal Utils +/** Internal Utils * - * @author 梦境迷离 - * @version 1.0,2022/3/18 + * @author + * 梦境迷离 + * @version 1.0,2022/3/18 */ object Utils { diff --git a/smt-cacheable-core/src/main/scala/org/bitlap/cacheable/core/ZIOCache.scala b/smt-cacheable-core/src/main/scala/org/bitlap/cacheable/core/ZIOCache.scala index bcd609029a965c2dd3df06e07ceda4d18f4c29af..f9661659d1e67b50c7ac3e53cab3abc57e73f984 100644 --- a/smt-cacheable-core/src/main/scala/org/bitlap/cacheable/core/ZIOCache.scala +++ b/smt-cacheable-core/src/main/scala/org/bitlap/cacheable/core/ZIOCache.scala @@ -23,11 +23,11 @@ package org.bitlap.cacheable.core import zio.ZIO -/** - * Redis Cache for ZIO. +/** Redis Cache for ZIO. * - * @author 梦境迷离 - * @version 2.0,2022/3/18 + * @author + * 梦境迷离 + * @version 2.0,2022/3/18 */ trait ZIOCache[R, E, T] extends Cache[ZIO[R, E, T]] { diff --git a/smt-cacheable-core/src/main/scala/org/bitlap/cacheable/core/ZIOUpdateCache.scala b/smt-cacheable-core/src/main/scala/org/bitlap/cacheable/core/ZIOUpdateCache.scala index 04d1642a396b62426f4373818cbd90a618f94c71..d4bc3755c0a4ffe9fffda5d72183b9f88d019369 100644 --- a/smt-cacheable-core/src/main/scala/org/bitlap/cacheable/core/ZIOUpdateCache.scala +++ b/smt-cacheable-core/src/main/scala/org/bitlap/cacheable/core/ZIOUpdateCache.scala @@ -23,11 +23,11 @@ package org.bitlap.cacheable.core import zio.ZIO -/** - * Redis Update Cache for ZIO. +/** Redis Update Cache for ZIO. * - * @author 梦境迷离 - * @version 2.0,2022/3/18 + * @author + * 梦境迷离 + * @version 2.0,2022/3/18 */ trait ZIOUpdateCache[R, E, T] extends Cache[ZIO[R, E, T]] { diff --git a/smt-cacheable-core/src/main/scala/org/bitlap/cacheable/core/ZStreamCache.scala b/smt-cacheable-core/src/main/scala/org/bitlap/cacheable/core/ZStreamCache.scala index 09140898e2674931efb26c1cb7130db573fb273a..5077a86a0f12ae9ff485810684cbeb46faf89bb7 100644 --- a/smt-cacheable-core/src/main/scala/org/bitlap/cacheable/core/ZStreamCache.scala +++ b/smt-cacheable-core/src/main/scala/org/bitlap/cacheable/core/ZStreamCache.scala @@ -23,11 +23,11 @@ package org.bitlap.cacheable.core import zio.stream.ZStream -/** - * Redis Cache for ZStream. +/** Redis Cache for ZStream. * - * @author 梦境迷离 - * @version 2.0,2022/3/19 + * @author + * 梦境迷离 + * @version 2.0,2022/3/19 */ trait ZStreamCache[R, E, T] extends Cache[ZStream[R, E, T]] { diff --git a/smt-cacheable-core/src/main/scala/org/bitlap/cacheable/core/ZStreamUpdateCache.scala b/smt-cacheable-core/src/main/scala/org/bitlap/cacheable/core/ZStreamUpdateCache.scala index c66616f99b95d8e4bb6c63434be991fe921f2cbf..149bff81f9f645fe7b758a967b1cfd548c2d0ba1 100644 --- a/smt-cacheable-core/src/main/scala/org/bitlap/cacheable/core/ZStreamUpdateCache.scala +++ b/smt-cacheable-core/src/main/scala/org/bitlap/cacheable/core/ZStreamUpdateCache.scala @@ -23,11 +23,11 @@ package org.bitlap.cacheable.core import zio.stream.ZStream -/** - * Redis Update Cache for ZStream. +/** Redis Update Cache for ZStream. * - * @author 梦境迷离 - * @version 2.0,2022/3/19 + * @author + * 梦境迷离 + * @version 2.0,2022/3/19 */ trait ZStreamUpdateCache[R, E, T] extends Cache[ZStream[R, E, T]] { diff --git a/smt-cacheable-core/src/main/scala/org/bitlap/cacheable/core/cacheEvict.scala b/smt-cacheable-core/src/main/scala/org/bitlap/cacheable/core/cacheEvict.scala index 7c7bfae04d46f1e00c8810875eb185d7c60cd589..c251eb733ab8aac7a8a6c57d3f1255b7366194f3 100644 --- a/smt-cacheable-core/src/main/scala/org/bitlap/cacheable/core/cacheEvict.scala +++ b/smt-cacheable-core/src/main/scala/org/bitlap/cacheable/core/cacheEvict.scala @@ -25,14 +25,16 @@ import org.bitlap.cacheable.core.macros.CacheEvictMacro import scala.annotation.{ compileTimeOnly, StaticAnnotation } -/** - * A distributed cache for zio. +/** A distributed cache for zio. * - * @author 梦境迷离 - * @param local Whether to enable local cache by caffeine. Must be a named parameter. - * @param values Indicates which caches the purge operation occurs on. Must be a named parameter. - * @since 2022/3/18 - * @version 1.0 + * @author + * 梦境迷离 + * @param local + * Whether to enable local cache by caffeine. Must be a named parameter. + * @param values + * Indicates which caches the purge operation occurs on. Must be a named parameter. + * @since 2022/3/18 + * @version 1.0 */ @compileTimeOnly("enable macro to expand macro annotations") final class cacheEvict(local: Boolean = true, values: List[String] = Nil) extends StaticAnnotation { diff --git a/smt-cacheable-core/src/main/scala/org/bitlap/cacheable/core/cacheable.scala b/smt-cacheable-core/src/main/scala/org/bitlap/cacheable/core/cacheable.scala index f271123ab8a61ed6ea0def6447a74faa22462c26..e5b1e19db02b0944f9590a3127ce5789fcb2b957 100644 --- a/smt-cacheable-core/src/main/scala/org/bitlap/cacheable/core/cacheable.scala +++ b/smt-cacheable-core/src/main/scala/org/bitlap/cacheable/core/cacheable.scala @@ -25,13 +25,14 @@ import org.bitlap.cacheable.core.macros.CacheableMacro.CacheableProcessor import scala.annotation.{ compileTimeOnly, StaticAnnotation } -/** - * A distributed cache for zio. +/** A distributed cache for zio. * - * @author 梦境迷离 - * @param local Whether to enable local cache by caffeine. - * @since 2022/3/18 - * @version 1.0 + * @author + * 梦境迷离 + * @param local + * Whether to enable local cache by caffeine. + * @since 2022/3/18 + * @version 1.0 */ @compileTimeOnly("enable macro to expand macro annotations") final class cacheable(local: Boolean = true) extends StaticAnnotation { diff --git a/smt-cacheable-core/src/main/scala/org/bitlap/cacheable/core/macros/AbstractMacroProcessor.scala b/smt-cacheable-core/src/main/scala/org/bitlap/cacheable/core/macros/AbstractMacroProcessor.scala index 87f2fc0d66769e58be2cea6cd39bbc9607b21f6e..01b240705e5a1f004ec5f2bdb8c180458392f27d 100644 --- a/smt-cacheable-core/src/main/scala/org/bitlap/cacheable/core/macros/AbstractMacroProcessor.scala +++ b/smt-cacheable-core/src/main/scala/org/bitlap/cacheable/core/macros/AbstractMacroProcessor.scala @@ -27,20 +27,19 @@ import scala.annotation.tailrec import scala.collection.mutable.ListBuffer import scala.reflect.macros.whitebox -/** - * @author 梦境迷离 - * @since 2022/3/19 - * @version 1.0 +/** @author + * 梦境迷离 + * @since 2022/3/19 + * @version 1.0 */ abstract class AbstractMacroProcessor(val c: whitebox.Context) { import c.universe._ - /** - * Output ast result. + /** Output ast result. * - * @param force - * @param resTree + * @param force + * @param resTree */ def printTree(force: Boolean, resTree: Tree): Unit = c.info( @@ -50,19 +49,19 @@ abstract class AbstractMacroProcessor(val c: whitebox.Context) { force = false ) - /** - * Find the specified method Name in the enclosing class definition. + /** Find the specified method Name in the enclosing class definition. * - * @param t - * @return Return a optional [[scala.reflect.api.Names#TermName]] + * @param t + * @return + * Return a optional [[scala.reflect.api.Names#TermName]] */ def findDefDefInEnclosingClass(t: Name): Option[TermName] = getDefDefInEnclosingClass.find(_.decodedName.toString == t.decodedName.toString) - /** - * Find all method Name in the enclosing class definition. + /** Find all method Name in the enclosing class definition. * - * @return Return a sequence of [[scala.reflect.api.Names#TermName]] + * @return + * Return a sequence of [[scala.reflect.api.Names#TermName]] */ def getDefDefInEnclosingClass: Set[TermName] = { val buffer = ListBuffer[TermName]() @@ -92,10 +91,9 @@ abstract class AbstractMacroProcessor(val c: whitebox.Context) { buffer.result().toSet } - /** - * Get enclosing class name + /** Get enclosing class name * - * @return + * @return */ def getEnclosingClassName: String = c.enclosingClass match { diff --git a/smt-cacheable-core/src/main/scala/org/bitlap/cacheable/core/macros/CacheEvictMacro.scala b/smt-cacheable-core/src/main/scala/org/bitlap/cacheable/core/macros/CacheEvictMacro.scala index aca171d37003229b7d1b141ad02d6b76e951e314..5ab7dc7d849af4dfe1f2e27ada586158f3c14e0d 100644 --- a/smt-cacheable-core/src/main/scala/org/bitlap/cacheable/core/macros/CacheEvictMacro.scala +++ b/smt-cacheable-core/src/main/scala/org/bitlap/cacheable/core/macros/CacheEvictMacro.scala @@ -23,12 +23,12 @@ package org.bitlap.cacheable.core.macros import scala.reflect.macros.whitebox -/** - * Evict cache +/** Evict cache * - * @author 梦境迷离 - * @since 2022/3/19 - * @version 1.0 + * @author + * 梦境迷离 + * @since 2022/3/19 + * @version 1.0 */ object CacheEvictMacro { @@ -37,9 +37,9 @@ object CacheEvictMacro { import c.universe._ private lazy val resultValName: c.universe.TermName = TermName("$result") - private lazy val argsValName: c.universe.TermName = TermName("$args") + private lazy val argsValName: c.universe.TermName = TermName("$args") - private val parameters: Tuple2[Boolean, List[String]] = { + private val parameters: Tuple2[Boolean, List[String]] = c.prefix.tree match { case q"new cacheEvict(local=$local, values=$values)" => Tuple2( @@ -69,7 +69,6 @@ object CacheEvictMacro { case _ => c.abort(c.enclosingPosition, "Unexpected annotation pattern!") } - } def impl(annottees: c.universe.Expr[Any]*): c.universe.Expr[Any] = { val resTree = annottees.map(_.tree) match { @@ -107,9 +106,9 @@ object CacheEvictMacro { c.info( c.enclosingPosition, s"""These methods will remove from cache: $identities, key prefix is: $enclosingClassName, mode is: ${if ( - parameters._1 - ) "local" - else "redis"}""", + parameters._1 + ) "local" + else "redis"}""", true ) val newBody = diff --git a/smt-cacheable-core/src/main/scala/org/bitlap/cacheable/core/macros/CacheableMacro.scala b/smt-cacheable-core/src/main/scala/org/bitlap/cacheable/core/macros/CacheableMacro.scala index 349f5a66bde2607cdcbb0d9f6ae97057f7df7950..deb6ed834d1d1beb3bfd62f7a280fe21aa82fac9 100644 --- a/smt-cacheable-core/src/main/scala/org/bitlap/cacheable/core/macros/CacheableMacro.scala +++ b/smt-cacheable-core/src/main/scala/org/bitlap/cacheable/core/macros/CacheableMacro.scala @@ -23,12 +23,12 @@ package org.bitlap.cacheable.core.macros import scala.reflect.macros.whitebox -/** - * GetAndSet cache +/** GetAndSet cache * - * @author 梦境迷离 - * @since 2022/3/18 - * @version 1.0 + * @author + * 梦境迷离 + * @since 2022/3/18 + * @version 1.0 */ object CacheableMacro { @@ -37,16 +37,15 @@ object CacheableMacro { import c.universe._ private lazy val resultValName: c.universe.TermName = TermName("$result") - private lazy val keyValName: c.universe.TermName = TermName("$key") + private lazy val keyValName: c.universe.TermName = TermName("$key") - protected val local: Boolean = { + protected val local: Boolean = c.prefix.tree match { case q"new cacheable(local=$local)" => c.eval(c.Expr[Boolean](c.untypecheck(local.asInstanceOf[Tree].duplicate))) case q"new cacheable($local)" => c.eval(c.Expr[Boolean](c.untypecheck(local.asInstanceOf[Tree].duplicate))) case q"new cacheable()" => true } - } private def getParamsName(vparamss: List[List[ValDef]]): List[List[TermName]] = vparamss.map(_.map(_.name)) diff --git a/smt-cacheable-redis/src/main/scala/org/bitlap/cacheable/redis/Implicits.scala b/smt-cacheable-redis/src/main/scala/org/bitlap/cacheable/redis/Implicits.scala index d537e01d68f7084acad05d475e7185e4a427e5e5..3d89d0cd9d6cf77c56c04417ae00585fef7188b9 100644 --- a/smt-cacheable-redis/src/main/scala/org/bitlap/cacheable/redis/Implicits.scala +++ b/smt-cacheable-redis/src/main/scala/org/bitlap/cacheable/redis/Implicits.scala @@ -28,11 +28,11 @@ import zio.stream.ZStream import zio.Chunk import java.util.concurrent.atomic.AtomicLong -/** - * redis cache +/** redis cache * - * @author 梦境迷离 - * @version 1.0,2022/3/21 + * @author + * 梦境迷离 + * @version 1.0,2022/3/21 */ object Implicits { @@ -55,24 +55,25 @@ object Implicits { override def getIfPresent( business: => ZStream[Any, Throwable, T] )(identities: List[String], args: List[_]): ZStream[Any, Throwable, T] = { - val key = cacheKey(identities) - val field = cacheField(args) - lazy val ret = business.runCollect.tap(r => ZRedisService.hSet[Chunk[T]](key, field, r)) + val key = cacheKey(identities) + val field = cacheField(args) + lazy val ret = business.runCollect.tap(r => ZRedisService.hSet[Chunk[T]](key, field, r)) lazy val resultFun = (chunk: Chunk[T]) => if (chunk.isEmpty) ret else ZIO.succeed(chunk) - lazy val count = new AtomicLong(0L) + lazy val count = new AtomicLong(0L) for { // TODO fix it, cannot get case class from redis and not lock cacheValue <- ZStream.fromEffect(ZRedisService.hGet[Chunk[T]](key, field)).map(_.getOrElse(Chunk.empty)) _ <- Utils .debugS(s"Redis ZStream getIfPresent >>> identity:[$key],field:[$field],cacheValue:[$cacheValue]") .when(!ZRedisConfiguration.disabledLog) - ret <- ZStream.fromEffect(resultFun(cacheValue)) + ret <- ZStream.fromEffect(resultFun(cacheValue)) result <- ZStream.fromIterable(ret) - _ <- Utils - .debugS( - s"Redis ZStream getIfPresent >>> identity:[$key],field(${count.incrementAndGet()}):[$field],result:[$result]" - ) - .when(!ZRedisConfiguration.disabledLog) + _ <- + Utils + .debugS( + s"Redis ZStream getIfPresent >>> identity:[$key],field(${count.incrementAndGet()}):[$field],result:[$result]" + ) + .when(!ZRedisConfiguration.disabledLog) } yield result } } @@ -91,7 +92,7 @@ object Implicits { override def getIfPresent( business: => ZIO[Any, Throwable, T] )(identities: List[String], args: List[_]): ZIO[Any, Throwable, T] = { - val key = cacheKey(identities) + val key = cacheKey(identities) val field = cacheField(args) for { cacheValue <- ZRedisService.hGet[T](key, field) diff --git a/smt-cacheable-redis/src/main/scala/org/bitlap/cacheable/redis/ZRedisConfiguration.scala b/smt-cacheable-redis/src/main/scala/org/bitlap/cacheable/redis/ZRedisConfiguration.scala index 32b7b119f63f79766f9acf46250f6fd28101baa2..c8662772c07ca1e2a011c6123f4f7eec13b753a0 100644 --- a/smt-cacheable-redis/src/main/scala/org/bitlap/cacheable/redis/ZRedisConfiguration.scala +++ b/smt-cacheable-redis/src/main/scala/org/bitlap/cacheable/redis/ZRedisConfiguration.scala @@ -28,17 +28,17 @@ import zio.schema.codec.{ Codec, JsonCodec } import zio.{ Has, Layer, ULayer, ZLayer } import zio.logging.Logging -/** - * redis configuration +/** redis configuration * - * @author 梦境迷离 - * @since 2022/1/10 - * @version 2.0 + * @author + * 梦境迷离 + * @since 2022/1/10 + * @version 2.0 */ object ZRedisConfiguration { - private lazy val conf: Config = ConfigFactory.load("reference.conf") - private lazy val custom: Config = ConfigFactory.load("application.conf").withFallback(conf) + private lazy val conf: Config = ConfigFactory.load("reference.conf") + private lazy val custom: Config = ConfigFactory.load("application.conf").withFallback(conf) private lazy val redisConf: RedisConfig = RedisConfig(custom.getString("redis.host"), custom.getInt("redis.port")) private[redis] lazy val disabledLog: Boolean = custom.getBoolean("redis.disabledLog") diff --git a/smt-cacheable-redis/src/main/scala/org/bitlap/cacheable/redis/ZRedisLive.scala b/smt-cacheable-redis/src/main/scala/org/bitlap/cacheable/redis/ZRedisLive.scala index c9513a49fa91a2accebc97847e386ae2684bc883..1160ea8b8ec3eb60b77d3437aef587113c921322 100644 --- a/smt-cacheable-redis/src/main/scala/org/bitlap/cacheable/redis/ZRedisLive.scala +++ b/smt-cacheable-redis/src/main/scala/org/bitlap/cacheable/redis/ZRedisLive.scala @@ -25,10 +25,11 @@ import zio.{ redis, Has, ULayer, ZIO, ZLayer } import zio.redis.{ Redis, RedisError } import zio.schema.Schema -/** - * @author 梦境迷离 - * @see https://zio.dev/version-1.x/datatypes/contextual/#module-pattern-20 - * @version 2.0,2022/1/17 +/** @author + * 梦境迷离 + * @see + * https://zio.dev/version-1.x/datatypes/contextual/#module-pattern-20 + * @version 2.0,2022/1/17 */ case class ZRedisLive(private val rs: Redis) extends ZRedisService { diff --git a/smt-cacheable-redis/src/main/scala/org/bitlap/cacheable/redis/ZRedisService.scala b/smt-cacheable-redis/src/main/scala/org/bitlap/cacheable/redis/ZRedisService.scala index 4ad571f34f58f8cf116e4781d54dc6b53c075e61..3c88c35b57580174ef379b990b5553f1da2722b0 100644 --- a/smt-cacheable-redis/src/main/scala/org/bitlap/cacheable/redis/ZRedisService.scala +++ b/smt-cacheable-redis/src/main/scala/org/bitlap/cacheable/redis/ZRedisService.scala @@ -25,39 +25,38 @@ import zio.redis.RedisError import zio.schema.Schema import zio.{ IO, Layer, ZIO } -/** - * Redis service. +/** Redis service. * - * @author 梦境迷离 - * @version 2.0,2022/1/10 + * @author + * 梦境迷离 + * @version 2.0,2022/1/10 */ trait ZRedisService { - /** - * @param key - * @return Long + /** @param key + * @return + * Long */ def del(key: String): ZIO[ZRedisCacheService, RedisError, Long] - /** - * @param key - * @param field - * @param value - * @return Long + /** @param key + * @param field + * @param value + * @return + * Long */ def hSet[T: Schema](key: String, field: String, value: T): ZIO[ZRedisCacheService, RedisError, Long] - /** - * @param key - * @param field - * @return Option[T] + /** @param key + * @param field + * @return + * Option[T] */ def hGet[T: Schema](key: String, field: String): ZIO[ZRedisCacheService, RedisError, Option[T]] - /** - * @param key - * @tparam T - * @return + /** @param key + * @tparam T + * @return */ def hGetAll[T: Schema](key: String): ZIO[ZRedisCacheService, RedisError, Map[String, T]] diff --git a/smt-cacheable-redis/src/main/scala/org/bitlap/cacheable/redis/redis.scala b/smt-cacheable-redis/src/main/scala/org/bitlap/cacheable/redis/redis.scala index fea6b8516b345e67df513619196a1b19273dedc3..95e3aa47989f7d5f44c35f67a82ab857f615f83e 100644 --- a/smt-cacheable-redis/src/main/scala/org/bitlap/cacheable/redis/redis.scala +++ b/smt-cacheable-redis/src/main/scala/org/bitlap/cacheable/redis/redis.scala @@ -23,10 +23,10 @@ package org.bitlap.cacheable import zio.Has -/** - * @author 梦境迷离 - * @since 2022/2/27 - * @version 1.0 +/** @author + * 梦境迷离 + * @since 2022/2/27 + * @version 1.0 */ package object redis { diff --git a/smt-cacheable-redis/src/test/scala/org/bitlap/cacheable/redis/CacheEvictTest.scala b/smt-cacheable-redis/src/test/scala/org/bitlap/cacheable/redis/CacheEvictTest.scala index 59e560a60d129c900965f8e6e8e8dbe3085475a5..bb6d3393e263bf18ecb9e321520a10877d6a8faa 100644 --- a/smt-cacheable-redis/src/test/scala/org/bitlap/cacheable/redis/CacheEvictTest.scala +++ b/smt-cacheable-redis/src/test/scala/org/bitlap/cacheable/redis/CacheEvictTest.scala @@ -29,10 +29,10 @@ import zio.stream.ZStream import scala.util.Random -/** - * @author 梦境迷离 - * @since 2022/3/19 - * @version 1.0 +/** @author + * 梦境迷离 + * @since 2022/3/19 + * @version 1.0 */ class CacheEvictTest extends AnyFlatSpec with Matchers { @@ -45,7 +45,7 @@ class CacheEvictTest extends AnyFlatSpec with Matchers { def readIOFunction: String = "hello world" - val readIOMethodName = "readIOFunction" + val readIOMethodName = "readIOFunction" val readStreamMethodName = "readStreamFunction" "cacheEvict1" should "ok" in { diff --git a/smt-cacheable-redis/src/test/scala/org/bitlap/cacheable/redis/CacheableTest.scala b/smt-cacheable-redis/src/test/scala/org/bitlap/cacheable/redis/CacheableTest.scala index 708d9fc421187e43869edf271f3450ddf9067dff..e6cfb5d86e92e52911213aa48f455998bfa99bba 100644 --- a/smt-cacheable-redis/src/test/scala/org/bitlap/cacheable/redis/CacheableTest.scala +++ b/smt-cacheable-redis/src/test/scala/org/bitlap/cacheable/redis/CacheableTest.scala @@ -30,14 +30,14 @@ import zio.Chunk import scala.util.Random -/** - * @author 梦境迷离 - * @since 2021/8/7 - * @version 1.0 +/** @author + * 梦境迷离 + * @since 2021/8/7 + * @version 1.0 */ class CacheableTest extends AnyFlatSpec with Matchers { - val runtime = zio.Runtime.default + val runtime = zio.Runtime.default val readIOMethodName = "readIOFunction" "cacheable1" should "ok" in { @@ -67,9 +67,9 @@ class CacheableTest extends AnyFlatSpec with Matchers { println(chunk) val result = runtime.unsafeRun(for { - _ <- ZRedisService.del("CacheableTest-readStreamFunction") + _ <- ZRedisService.del("CacheableTest-readStreamFunction") method <- readStreamFunction(1, "hello").runCollect - cache <- ZRedisService.hGet[Chunk[String]]("CacheableTest-readStreamFunction", "1-hello") + cache <- ZRedisService.hGet[Chunk[String]]("CacheableTest-readStreamFunction", "1-hello") } yield method -> cache.getOrElse(Chunk.empty)) result._1 shouldEqual result._2 } @@ -82,7 +82,7 @@ class CacheableTest extends AnyFlatSpec with Matchers { ZStream.fromEffect(ZIO.effect(cacheValue)) val result = runtime.unsafeRun(for { - _ <- ZRedisService.del("CacheableTest-readEntityStreamFunction") + _ <- ZRedisService.del("CacheableTest-readEntityStreamFunction") method <- readEntityStreamFunction(1, "hello").runHead } yield method) @@ -97,9 +97,9 @@ class CacheableTest extends AnyFlatSpec with Matchers { ZIO.effect(cacheValue) val result = runtime.unsafeRun(for { - _ <- ZRedisService.del("CacheableTest-readEntityIOFunction") + _ <- ZRedisService.del("CacheableTest-readEntityIOFunction") method <- readEntityIOFunction(1, "hello") - cache <- ZRedisService.hGet[CacheValue]("CacheableTest-readEntityIOFunction", "1-hello") + cache <- ZRedisService.hGet[CacheValue]("CacheableTest-readEntityIOFunction", "1-hello") } yield Some(method) -> cache) result._1 shouldEqual result._2 diff --git a/smt-cacheable-redis/src/test/scala/org/bitlap/cacheable/redis/CustomCacheableTest.scala b/smt-cacheable-redis/src/test/scala/org/bitlap/cacheable/redis/CustomCacheableTest.scala index db56afd0c014e6e5dbf4fc57674fc44308899042..485ed465d6b7e6afb0ecb333e11d988a59d43c63 100644 --- a/smt-cacheable-redis/src/test/scala/org/bitlap/cacheable/redis/CustomCacheableTest.scala +++ b/smt-cacheable-redis/src/test/scala/org/bitlap/cacheable/redis/CustomCacheableTest.scala @@ -30,10 +30,10 @@ import zio.schema.{ Schema, StandardType } import scala.util.Random -/** - * @author 梦境迷离 - * @since 2022/3/20 - * @version 1.0 +/** @author + * 梦境迷离 + * @since 2022/3/20 + * @version 1.0 */ class CustomCacheableTest extends AnyFlatSpec with Matchers { diff --git a/smt-csv-core/src/main/scala/org/bitlap/csv/core/Converter.scala b/smt-csv-core/src/main/scala/org/bitlap/csv/core/Converter.scala index dd045e0db14ac393cc7fbeff1284488b18e0b2a0..0c1eadd883114af9c73804c054518d656ee807c8 100644 --- a/smt-csv-core/src/main/scala/org/bitlap/csv/core/Converter.scala +++ b/smt-csv-core/src/main/scala/org/bitlap/csv/core/Converter.scala @@ -23,12 +23,12 @@ package org.bitlap.csv.core import scala.collection.immutable.{ :: => Cons } -/** - * Csv encoder and decoder. +/** Csv encoder and decoder. * - * @author 梦境迷离 - * @since 2022/04/27 - * @version 1.0 + * @author + * 梦境迷离 + * @since 2022/04/27 + * @version 1.0 */ trait Converter[T] { @@ -97,7 +97,7 @@ object Converter { case Nil => Some(Nil) case Cons(s, ss) => for { - x <- ec.toScala(s) + x <- ec.toScala(s) xs <- listCsvLinesConverter(ss)(ec) } yield Cons(x, xs) } diff --git a/smt-csv-core/src/main/scala/org/bitlap/csv/core/Csvable.scala b/smt-csv-core/src/main/scala/org/bitlap/csv/core/Csvable.scala index 284dae3559c22135be9a21e5aa660a26dceb4d7b..7aae025919d0f2f95304b0ed19d3b2000ff9d176 100644 --- a/smt-csv-core/src/main/scala/org/bitlap/csv/core/Csvable.scala +++ b/smt-csv-core/src/main/scala/org/bitlap/csv/core/Csvable.scala @@ -21,20 +21,20 @@ package org.bitlap.csv.core -/** - * a Custom Csv encoder. +/** a Custom Csv encoder. * - * @author 梦境迷离 - * @since 2022/04/27 - * @version 1.0 + * @author + * 梦境迷离 + * @since 2022/04/27 + * @version 1.0 */ trait Csvable[T] { - /** - * API for processing a specific field of case class object. + /** API for processing a specific field of case class object. * - * @param t case class object - * @return + * @param t + * case class object + * @return */ def _toCsvString(t: T): String diff --git a/smt-csv-core/src/main/scala/org/bitlap/csv/core/CsvableBuilder.scala b/smt-csv-core/src/main/scala/org/bitlap/csv/core/CsvableBuilder.scala index 8724139cabf4927fff9412324926a14b65d8c502..6756466c057a69ff3d6d9590c89cfaf22dfc14cf 100644 --- a/smt-csv-core/src/main/scala/org/bitlap/csv/core/CsvableBuilder.scala +++ b/smt-csv-core/src/main/scala/org/bitlap/csv/core/CsvableBuilder.scala @@ -24,59 +24,63 @@ package org.bitlap.csv.core import org.bitlap.csv.core.macros.DeriveCsvableBuilder import java.io.File -/** - * Builder to create a custom Csv Encoder. +/** Builder to create a custom Csv Encoder. * - * @author 梦境迷离 - * @version 1.0,2022/4/30 + * @author + * 梦境迷离 + * @version 1.0,2022/4/30 */ class CsvableBuilder[T] { - /** - * Convert this CSV column string to any Scala types. + /** Convert this CSV column string to any Scala types. * - * @param scalaField The field in scala case class. - * @param value This function specifies how you want to convert this field to a CSV string. - * @tparam SF The field type, generally, it is not necessary to specify, but it is safer if specify. - * @return + * @param scalaField + * The field in scala case class. + * @param value + * This function specifies how you want to convert this field to a CSV string. + * @tparam SF + * The field type, generally, it is not necessary to specify, but it is safer if specify. + * @return */ def setField[SF](scalaField: T => SF, value: SF => String): CsvableBuilder[T] = macro DeriveCsvableBuilder.setFieldImpl[T, SF] - /** - * Create a custom builder for converting this scala value to CSV line string. + /** Create a custom builder for converting this scala value to CSV line string. * - * @param t The value of Scala case class. - * @param columnSeparator The separator for CSV column value. - * @return + * @param t + * The value of Scala case class. + * @param columnSeparator + * The separator for CSV column value. + * @return */ def convert(t: T, columnSeparator: Char): String = macro DeriveCsvableBuilder.convertOneImpl[T] - /** - * Make columnSeparator assign to `,` as default value. + /** Make columnSeparator assign to `,` as default value. */ def convert(t: T): String = macro DeriveCsvableBuilder.convertOneDefaultImpl[T] - /** - * Convert the sequence of Scala case class to CSV string. + /** Convert the sequence of Scala case class to CSV string. * - * @param ts The sequence of Scala case class. - * @param columnSeparator The separator for CSV column value. - * @return It combines CSV lines by '\n'. + * @param ts + * The sequence of Scala case class. + * @param columnSeparator + * The separator for CSV column value. + * @return + * It combines CSV lines by '\n'. */ def convert(ts: List[T], columnSeparator: Char): String = macro DeriveCsvableBuilder.convertImpl[T] - /** - * Make columnSeparator assign to `,` as default value. + /** Make columnSeparator assign to `,` as default value. */ def convert(ts: List[T]): String = macro DeriveCsvableBuilder.convertDefaultImpl[T] - /** - * Convert the sequence of Scala case class to CSV string and write to file. + /** Convert the sequence of Scala case class to CSV string and write to file. * - * @param ts The sequence of Scala case class. - * @param file File to save CSV string. - * @return + * @param ts + * The sequence of Scala case class. + * @param file + * File to save CSV string. + * @return */ def convertTo(ts: List[T], file: File): Boolean = macro DeriveCsvableBuilder.convertToFileImpl[T] diff --git a/smt-csv-core/src/main/scala/org/bitlap/csv/core/CsvableImplicits.scala b/smt-csv-core/src/main/scala/org/bitlap/csv/core/CsvableImplicits.scala index 5e0a2905357be663741d88665870a315603036d8..81accb50386cd73f990366aab087cbcdf2d4b676 100644 --- a/smt-csv-core/src/main/scala/org/bitlap/csv/core/CsvableImplicits.scala +++ b/smt-csv-core/src/main/scala/org/bitlap/csv/core/CsvableImplicits.scala @@ -21,9 +21,9 @@ package org.bitlap.csv.core -/** - * @author 梦境迷离 - * @version 1.0,2022/5/1 +/** @author + * 梦境迷离 + * @version 1.0,2022/5/1 */ trait CsvableImplicits { diff --git a/smt-csv-core/src/main/scala/org/bitlap/csv/core/FileUtils.scala b/smt-csv-core/src/main/scala/org/bitlap/csv/core/FileUtils.scala index a571de89e5f037b85d400530e58bdd964c382b7c..87342146c7c350da31d72f0deb1a6943ade0c3c7 100644 --- a/smt-csv-core/src/main/scala/org/bitlap/csv/core/FileUtils.scala +++ b/smt-csv-core/src/main/scala/org/bitlap/csv/core/FileUtils.scala @@ -28,9 +28,9 @@ import scala.util.control.Exception.ignoring import scala.collection.mutable.ListBuffer -/** - * @author 梦境迷离 - * @version 1.0,5/13/22 +/** @author + * 梦境迷离 + * @version 1.0,5/13/22 */ object FileUtils { @@ -40,23 +40,28 @@ object FileUtils { def using[R <: Closable, T](resource: => R)(f: R => T): T = try f(resource) - finally ignoring(classOf[Throwable]) apply { - resource.close() - } + finally + ignoring(classOf[Throwable]) apply { + resource.close() + } def writer(file: File, lines: List[String]): Boolean = { checkFile(file) val bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(file)) - try using(new PrintWriter(bufferedOutputStream, true)) { r => - lines.foreach(r.println) - } finally bufferedOutputStream.close() + try + using(new PrintWriter(bufferedOutputStream, true)) { r => + lines.foreach(r.println) + } + finally bufferedOutputStream.close() true } def reader(file: InputStream, charset: String = "UTF-8"): List[String] = - try using(Source.fromInputStream(new BufferedInputStream(file), charset)) { lines => - lines.getLines().toList - } finally file.close() + try + using(Source.fromInputStream(new BufferedInputStream(file), charset)) { lines => + lines.getLines().toList + } + finally file.close() def checkFile(file: File): Unit = { if (file.isDirectory) { @@ -68,7 +73,7 @@ object FileUtils { } def readFileFunc[T](reader: BufferedReader, func: String => Option[T]): List[Option[T]] = { - val ts = ListBuffer[Option[T]]() + val ts = ListBuffer[Option[T]]() var line: String = null FileUtils.using(new BufferedReader(reader)) { input => while ({ diff --git a/smt-csv-core/src/main/scala/org/bitlap/csv/core/Scalable.scala b/smt-csv-core/src/main/scala/org/bitlap/csv/core/Scalable.scala index c8379305a64f48214b8f4ad6f7b8e447c38e1801..2525be688ba0405d77f96f379ff02c20fb21f5b8 100644 --- a/smt-csv-core/src/main/scala/org/bitlap/csv/core/Scalable.scala +++ b/smt-csv-core/src/main/scala/org/bitlap/csv/core/Scalable.scala @@ -21,20 +21,20 @@ package org.bitlap.csv.core -/** - * a Custom Csv decoder. +/** a Custom Csv decoder. * - * @author 梦境迷离 - * @since 2022/04/30 - * @version 1.0 + * @author + * 梦境迷离 + * @since 2022/04/30 + * @version 1.0 */ trait Scalable[T] { - /** - * API for processing a specific column value of CSV line data. + /** API for processing a specific column value of CSV line data. * - * @param column The column value of CSV line data. - * @return + * @param column + * The column value of CSV line data. + * @return */ def _toScala(column: String): Option[T] } diff --git a/smt-csv-core/src/main/scala/org/bitlap/csv/core/ScalableBuilder.scala b/smt-csv-core/src/main/scala/org/bitlap/csv/core/ScalableBuilder.scala index 1c2180a85e4f86023d5ddc368470f415405c1669..28fd2340d533d38f0e60faa5eac438fe001cb8ce 100644 --- a/smt-csv-core/src/main/scala/org/bitlap/csv/core/ScalableBuilder.scala +++ b/smt-csv-core/src/main/scala/org/bitlap/csv/core/ScalableBuilder.scala @@ -24,59 +24,62 @@ package org.bitlap.csv.core import org.bitlap.csv.core.macros.DeriveScalableBuilder import java.io.InputStream -/** - * Builder to create a custom Csv Decoder. +/** Builder to create a custom Csv Decoder. * - * @author 梦境迷离 - * @version 1.0,2022/4/30 + * @author + * 梦境迷离 + * @version 1.0,2022/4/30 */ class ScalableBuilder[T] { - /** - * Convert any Scala types to this CSV column string. + /** Convert any Scala types to this CSV column string. * - * @param scalaField The field in scala case class. - * @param value This function specifies how you want to convert this CSV column to a scala type. - * @tparam SF The field type, generally, it is not necessary to specify, but it is safer if specify. - * @return + * @param scalaField + * The field in scala case class. + * @param value + * This function specifies how you want to convert this CSV column to a scala type. + * @tparam SF + * The field type, generally, it is not necessary to specify, but it is safer if specify. + * @return */ def setField[SF](scalaField: T => SF, value: String => SF): ScalableBuilder[T] = macro DeriveScalableBuilder.setFieldImpl[T, SF] - /** - * Create a custom builder for converting this CSV line to scala values. + /** Create a custom builder for converting this CSV line to scala values. * - * @param line One CSV line. - * @param columnSeparator The separator for CSV column value. - * @return + * @param line + * One CSV line. + * @param columnSeparator + * The separator for CSV column value. + * @return */ def convert(line: String, columnSeparator: Char): Option[T] = macro DeriveScalableBuilder.convertOneImpl[T] - /** - * Make columnSeparator assign to `,` as default value. + /** Make columnSeparator assign to `,` as default value. */ def convert(line: String): Option[T] = macro DeriveScalableBuilder.convertOneDefaultImpl[T] - /** - * Convert all CSV lines to the sequence of Scala case class. + /** Convert all CSV lines to the sequence of Scala case class. * - * @param lines All CSV lines. - * @param columnSeparator The separator for CSV column value. - * @return + * @param lines + * All CSV lines. + * @param columnSeparator + * The separator for CSV column value. + * @return */ def convert(lines: List[String], columnSeparator: Char): List[Option[T]] = macro DeriveScalableBuilder.convertImpl[T] - /** - * Make columnSeparator assign to `,` as default value. + /** Make columnSeparator assign to `,` as default value. */ def convert(lines: List[String]): List[Option[T]] = macro DeriveScalableBuilder.convertDefaultImpl[T] - /** - * Read all CSV lines of the file and convert them to the sequence of Scala case class. + /** Read all CSV lines of the file and convert them to the sequence of Scala case class. * - * @param file InputStream of the CSV file. - * @param charset String charset of the CSV file content. - * @return + * @param file + * InputStream of the CSV file. + * @param charset + * String charset of the CSV file content. + * @return */ def convertFrom(file: InputStream, charset: String): List[Option[T]] = macro DeriveScalableBuilder.convertFromFileImpl[T] diff --git a/smt-csv-core/src/main/scala/org/bitlap/csv/core/ScalableHelper.scala b/smt-csv-core/src/main/scala/org/bitlap/csv/core/ScalableHelper.scala index bffcbf36b4344d5d8e660169dcc01e06fa5fab41..f03745271eac23de8946c5503973f752d8efc80a 100644 --- a/smt-csv-core/src/main/scala/org/bitlap/csv/core/ScalableHelper.scala +++ b/smt-csv-core/src/main/scala/org/bitlap/csv/core/ScalableHelper.scala @@ -23,11 +23,11 @@ package org.bitlap.csv.core import java.io.{ BufferedReader, File, FileReader, InputStreamReader } -/** - * Tool class for parsing CSV files. +/** Tool class for parsing CSV files. * - * @author 梦境迷离 - * @version 1.0,2022/5/13 + * @author + * 梦境迷离 + * @version 1.0,2022/5/13 */ object ScalableHelper { diff --git a/smt-csv-core/src/main/scala/org/bitlap/csv/core/ScalableImplicits.scala b/smt-csv-core/src/main/scala/org/bitlap/csv/core/ScalableImplicits.scala index 8e407a1d2ad4c4cb08b1c612854f7ac5fecbf22d..1d3d567f229e868bb4ed023ac63d15b634d5b51e 100644 --- a/smt-csv-core/src/main/scala/org/bitlap/csv/core/ScalableImplicits.scala +++ b/smt-csv-core/src/main/scala/org/bitlap/csv/core/ScalableImplicits.scala @@ -21,9 +21,9 @@ package org.bitlap.csv.core -/** - * @author 梦境迷离 - * @version 1.0,2022/5/1 +/** @author + * 梦境迷离 + * @version 1.0,2022/5/1 */ trait ScalableImplicits { diff --git a/smt-csv-core/src/main/scala/org/bitlap/csv/core/StringUtils.scala b/smt-csv-core/src/main/scala/org/bitlap/csv/core/StringUtils.scala index a4735065b8ba048d54d4011a5af77709a79e39e1..fd13c8487964550928f843f954fdc227531cdd40 100644 --- a/smt-csv-core/src/main/scala/org/bitlap/csv/core/StringUtils.scala +++ b/smt-csv-core/src/main/scala/org/bitlap/csv/core/StringUtils.scala @@ -25,16 +25,16 @@ import java.util.regex.Pattern import scala.collection.mutable.ListBuffer import scala.util.matching.Regex -/** - * split csv column value by columnSeparator. +/** split csv column value by columnSeparator. * - * @author 梦境迷离 - * @version 1.0,2022/4/30 + * @author + * 梦境迷离 + * @version 1.0,2022/4/30 */ object StringUtils { - private val regex: Regex = "\\{(.*?)\\}".r - private val kvr: Regex = "(.*):(.*)".r + private val regex: Regex = "\\{(.*?)\\}".r + private val kvr: Regex = "(.*):(.*)".r private val pattern: Pattern = Pattern.compile(regex.toString()) def extraJsonPairs(input: String): String = { @@ -60,9 +60,9 @@ object StringUtils { } def splitColumns(line: => String, columnSeparator: Char): List[String] = { - val listBuffer = ListBuffer[String]() + val listBuffer = ListBuffer[String]() val columnBuffer = ListBuffer[Char]() - val chars = line.toCharArray + val chars = line.toCharArray var idx = 0 while (idx < chars.length) diff --git a/smt-csv-core/src/main/scala/org/bitlap/csv/core/macros/AbstractMacroProcessor.scala b/smt-csv-core/src/main/scala/org/bitlap/csv/core/macros/AbstractMacroProcessor.scala index d3540675173b07217e32180c6f4d93910fad1c08..fd51088ab13126d1039c55850fa55a4cf76d2153 100644 --- a/smt-csv-core/src/main/scala/org/bitlap/csv/core/macros/AbstractMacroProcessor.scala +++ b/smt-csv-core/src/main/scala/org/bitlap/csv/core/macros/AbstractMacroProcessor.scala @@ -25,12 +25,12 @@ import java.time.ZonedDateTime import java.time.format.DateTimeFormatter import scala.reflect.macros.blackbox -/** - * This is a generic implementation of macro handling, and subclasses need to inherit it to reduce redundant code. +/** This is a generic implementation of macro handling, and subclasses need to inherit it to reduce redundant code. * - * @author 梦境迷离 - * @since 2021/7/24 - * @version 1.0 + * @author + * 梦境迷离 + * @since 2021/7/24 + * @version 1.0 */ abstract class AbstractMacroProcessor(val c: blackbox.Context) { @@ -38,20 +38,22 @@ abstract class AbstractMacroProcessor(val c: blackbox.Context) { protected val packageName = q"_root_.org.bitlap.csv.core" - /** - * Get the list of case class constructor parameters and return the column index, column name, and parameter type that zip as a `List[((Int, Tree), Type)]`. + /** Get the list of case class constructor parameters and return the column index, column name, and parameter type + * that zip as a `List[((Int, Tree), Type)]`. * - * @param columnsFunc The function to get CSV row data temporary identifier, also known as a line. - * @tparam T Type of the case class. - * @return + * @param columnsFunc + * The function to get CSV row data temporary identifier, also known as a line. + * @tparam T + * Type of the case class. + * @return */ private[macros] def checkCaseClassZipAll[T: c.WeakTypeTag]( columnsFunc: TermName ): List[((Int, Tree), Type)] = { - val idxColumn = (i: Int) => q"$columnsFunc()($i)" - val params = getCaseClassParams[T]() - val paramsSize = params.size - val types = params.map(f => c.typecheck(tq"$f", c.TYPEmode).tpe) + val idxColumn = (i: Int) => q"$columnsFunc()($i)" + val params = getCaseClassParams[T]() + val paramsSize = params.size + val types = params.map(f => c.typecheck(tq"$f", c.TYPEmode).tpe) val indexColumns = (0 until paramsSize).toList.map(i => i -> idxColumn(i)) if (indexColumns.size != types.size) { c.abort(c.enclosingPosition, "The column num of CSV file is different from that in case class constructor!") @@ -60,11 +62,11 @@ abstract class AbstractMacroProcessor(val c: blackbox.Context) { indexColumns zip types } - /** - * Get only the symbol of the case class constructor parameters. + /** Get only the symbol of the case class constructor parameters. * - * @tparam T Type of the case class. - * @return + * @tparam T + * Type of the case class. + * @return */ private[macros] def getCaseClassParams[T: c.WeakTypeTag](): List[Symbol] = { val parameters = resolveParameters[T] @@ -74,13 +76,12 @@ abstract class AbstractMacroProcessor(val c: blackbox.Context) { parameters.flatten } - /** - * Print the expanded code of macro. + /** Print the expanded code of macro. * - * @param force - * @param resTree - * @tparam T - * @return + * @param force + * @param resTree + * @tparam T + * @return */ def exprPrintTree[T: c.WeakTypeTag](force: Boolean, resTree: c.Tree): c.Expr[T] = { c.info( @@ -92,42 +93,43 @@ abstract class AbstractMacroProcessor(val c: blackbox.Context) { c.Expr[T](resTree) } - /** - * Get the constructor symbol of the case class. + /** Get the constructor symbol of the case class. * - * @tparam T Type of the case class. - * @return The parameters may be currying, so it's a two-level list. + * @tparam T + * Type of the case class. + * @return + * The parameters may be currying, so it's a two-level list. */ private[macros] def resolveParameters[T: c.WeakTypeTag]: List[List[Symbol]] = c.weakTypeOf[T].resultType.member(TermName("")).typeSignature.paramLists - /** - * Get the `TypeName` of the class. + /** Get the `TypeName` of the class. * - * @tparam T Type of the case class. - * @return + * @tparam T + * Type of the case class. + * @return */ private[macros] def resolveClazzTypeName[T: c.WeakTypeTag]: c.universe.TypeName = TypeName(c.weakTypeOf[T].typeSymbol.name.decodedName.toString) - /** - * Get the list of case class constructor parameters and return the column index and parameter type that zip as a `List[(Int, Type)])`. + /** Get the list of case class constructor parameters and return the column index and parameter type that zip as a + * `List[(Int, Type)])`. * - * @tparam T Type of the case class. - * @return + * @tparam T + * Type of the case class. + * @return */ private[macros] def checkCaseClassZip[T: c.WeakTypeTag]: (List[String], List[(Int, Type)]) = { - val params = getCaseClassParams[T]() + val params = getCaseClassParams[T]() val paramsSize = params.size - val names = params.map(p => p.name.decodedName.toString) + val names = params.map(p => p.name.decodedName.toString) names -> params.zip(0 until paramsSize).map(f => f._2 -> c.typecheck(tq"${f._1}", c.TYPEmode).tpe) } - /** - * Get the builderId of the current class which generated by *Builder,apply macro. + /** Get the builderId of the current class which generated by *Builder,apply macro. * - * @param annoBuilderPrefix - * @return + * @param annoBuilderPrefix + * @return */ private[macros] def getBuilderId(annoBuilderPrefix: String): Int = c.prefix.actualType.toString.replace(annoBuilderPrefix, "").toInt diff --git a/smt-csv-core/src/main/scala/org/bitlap/csv/core/macros/DeriveCsvableBuilder.scala b/smt-csv-core/src/main/scala/org/bitlap/csv/core/macros/DeriveCsvableBuilder.scala index acdbeb1d16f8072d3218e3572f3f1923c0f26fd4..3c695cbae51e663dae8ce549172a8659aee941cb 100644 --- a/smt-csv-core/src/main/scala/org/bitlap/csv/core/macros/DeriveCsvableBuilder.scala +++ b/smt-csv-core/src/main/scala/org/bitlap/csv/core/macros/DeriveCsvableBuilder.scala @@ -27,9 +27,9 @@ import scala.collection.mutable import scala.reflect.macros.whitebox import java.io.File -/** - * @author 梦境迷离 - * @version 1.0,2022/4/29 +/** @author + * 梦境迷离 + * @version 1.0,2022/4/29 */ class DeriveCsvableBuilder(override val c: whitebox.Context) extends AbstractMacroProcessor(c) { @@ -39,16 +39,16 @@ class DeriveCsvableBuilder(override val c: whitebox.Context) extends AbstractMac private val builderFunctionPrefix = "_CsvableBuilderFunction$" - private val innerTName = q"_t" - private val innerTmpTermName = TermName("_tt") - private val csvableInstanceTermName = TermName("_csvableInstance") + private val innerTName = q"_t" + private val innerTmpTermName = TermName("_tt") + private val csvableInstanceTermName = TermName("_csvableInstance") private val csvableImplClassNamePrefix = "_CsvAnno$" - private val funcArgsTempTermName = TermName("temp") + private val funcArgsTempTermName = TermName("temp") // scalafmt: { maxColumn = 400 } def setFieldImpl[T: WeakTypeTag, SF: WeakTypeTag](scalaField: Expr[T => SF], value: Expr[SF => String]): Expr[CsvableBuilder[T]] = { val Function(_, Select(_, termName)) = scalaField.tree - val builderId = getBuilderId(annoBuilderPrefix) + val builderId = getBuilderId(annoBuilderPrefix) MacroCache.builderFunctionTrees.getOrElseUpdate(builderId, mutable.Map.empty).update(termName.toString, value) val tree = q"new ${c.prefix.actualType}" exprPrintTree[CsvableBuilder[T]](force = false, tree) @@ -73,7 +73,7 @@ class DeriveCsvableBuilder(override val c: whitebox.Context) extends AbstractMac deriveFullIntoFileCsvableImpl[T](ts, file, c.Expr[Char](q"','")) private def deriveBuilderApplyImpl[T: WeakTypeTag]: Expr[CsvableBuilder[T]] = { - val className = TypeName(annoBuilderPrefix + MacroCache.getBuilderId) + val className = TypeName(annoBuilderPrefix + MacroCache.getBuilderId) val caseClazzName = TypeName(weakTypeOf[T].typeSymbol.name.decodedName.toString) val tree = q""" @@ -97,7 +97,7 @@ class DeriveCsvableBuilder(override val c: whitebox.Context) extends AbstractMac // scalafmt: { maxColumn = 400 } private def deriveFullIntoFileCsvableImpl[T: WeakTypeTag](ts: Expr[List[T]], file: Expr[File], columnSeparator: Expr[Char]): Expr[Boolean] = { - val clazzName = resolveClazzTypeName[T] + val clazzName = resolveClazzTypeName[T] val (customTrees, preTrees) = getCustomPreTress val tree = q""" ..$preTrees @@ -113,7 +113,7 @@ class DeriveCsvableBuilder(override val c: whitebox.Context) extends AbstractMac // scalafmt: { maxColumn = 400 } private def deriveFullCsvableImpl[T: WeakTypeTag](ts: Expr[List[T]], columnSeparator: Expr[Char]): Expr[String] = { - val clazzName = resolveClazzTypeName[T] + val clazzName = resolveClazzTypeName[T] val (customTrees, preTrees) = getCustomPreTress val tree = q""" @@ -128,9 +128,9 @@ class DeriveCsvableBuilder(override val c: whitebox.Context) extends AbstractMac } private def getAnnoClassObject[T: WeakTypeTag](customTrees: mutable.Map[String, Any], columnSeparator: Expr[Char]): Tree = { - val clazzName = resolveClazzTypeName[T] + val clazzName = resolveClazzTypeName[T] val annoClassName = TermName(csvableImplClassNamePrefix + MacroCache.getIdentityId) - val separator = q"$columnSeparator" + val separator = q"$columnSeparator" q""" object $annoClassName extends $packageName.Csvable[$clazzName] { var $innerTmpTermName: $clazzName = _ @@ -147,10 +147,10 @@ class DeriveCsvableBuilder(override val c: whitebox.Context) extends AbstractMac } private def deriveCsvableImpl[T: WeakTypeTag](t: Expr[T], columnSeparator: Expr[Char]): Expr[String] = { - val clazzName = resolveClazzTypeName[T] + val clazzName = resolveClazzTypeName[T] val (customTrees, preTrees) = getCustomPreTress - val annoClassName = TermName(csvableImplClassNamePrefix + MacroCache.getIdentityId) - val separator = q"$columnSeparator" + val annoClassName = TermName(csvableImplClassNamePrefix + MacroCache.getIdentityId) + val separator = q"$columnSeparator" val tree = q""" @@ -170,9 +170,9 @@ class DeriveCsvableBuilder(override val c: whitebox.Context) extends AbstractMac // scalafmt: { maxColumn = 400 } private def fieldsToString[T: WeakTypeTag](innerVarTermName: TermName, customTrees: mutable.Map[String, Any]): List[Tree] = { - val clazzName = resolveClazzTypeName[T] + val clazzName = resolveClazzTypeName[T] val (fieldNames, indexTypes) = checkCaseClassZip - val indexByName = (i: Int) => TermName(fieldNames(i)) + val indexByName = (i: Int) => TermName(fieldNames(i)) indexTypes.map { idxType => val customFunction = () => q"${TermName(builderFunctionPrefix + fieldNames(idxType._1))}.apply($innerVarTermName.${indexByName(idxType._1)})" idxType._2 match { diff --git a/smt-csv-core/src/main/scala/org/bitlap/csv/core/macros/DeriveScalableBuilder.scala b/smt-csv-core/src/main/scala/org/bitlap/csv/core/macros/DeriveScalableBuilder.scala index a14dc9b1a5a25934b94f747c19e6512c78267b35..b960fbe4bcc7c66852220e470ab1babd4a778528 100644 --- a/smt-csv-core/src/main/scala/org/bitlap/csv/core/macros/DeriveScalableBuilder.scala +++ b/smt-csv-core/src/main/scala/org/bitlap/csv/core/macros/DeriveScalableBuilder.scala @@ -27,9 +27,9 @@ import java.io.InputStream import scala.collection.mutable import scala.reflect.macros.whitebox -/** - * @author 梦境迷离 - * @version 1.0,2022/4/29 +/** @author + * 梦境迷离 + * @version 1.0,2022/4/29 */ class DeriveScalableBuilder(override val c: whitebox.Context) extends AbstractMacroProcessor(c) { @@ -39,16 +39,16 @@ class DeriveScalableBuilder(override val c: whitebox.Context) extends AbstractMa private val builderFunctionPrefix = "_ScalableBuilderFunction$" - private val innerColumnFuncTermName = TermName("_columns") - private val innerLName = q"_l" - private val innerTempTermName = TermName("_line") - private val scalableInstanceTermName = TermName("_scalableInstance") + private val innerColumnFuncTermName = TermName("_columns") + private val innerLName = q"_l" + private val innerTempTermName = TermName("_line") + private val scalableInstanceTermName = TermName("_scalableInstance") private val scalableImplClassNamePrefix = "_ScalaAnno$" // scalafmt: { maxColumn = 400 } def setFieldImpl[T: WeakTypeTag, SF: WeakTypeTag](scalaField: Expr[T => SF], value: Expr[String => SF]): Expr[ScalableBuilder[T]] = { val Function(_, Select(_, termName)) = scalaField.tree - val builderId = getBuilderId(annoBuilderPrefix) + val builderId = getBuilderId(annoBuilderPrefix) MacroCache.builderFunctionTrees.getOrElseUpdate(builderId, mutable.Map.empty).update(termName.toString, value) val tree = q"new ${c.prefix.actualType}" exprPrintTree[ScalableBuilder[T]](force = false, tree) @@ -83,7 +83,7 @@ class DeriveScalableBuilder(override val c: whitebox.Context) extends AbstractMa } private def deriveBuilderApplyImpl[T: WeakTypeTag]: Expr[ScalableBuilder[T]] = { - val className = TypeName(annoBuilderPrefix + MacroCache.getBuilderId) + val className = TypeName(annoBuilderPrefix + MacroCache.getBuilderId) val caseClazzName = TypeName(weakTypeOf[T].typeSymbol.name.decodedName.toString) val tree = q""" @@ -166,12 +166,12 @@ class DeriveScalableBuilder(override val c: whitebox.Context) extends AbstractMa // scalafmt: { maxColumn = 400 } private def scalableBody[T: WeakTypeTag](clazzName: TypeName, innerFuncTermName: TermName): Tree = { val customTrees = MacroCache.builderFunctionTrees.getOrElse(getBuilderId(annoBuilderPrefix), mutable.Map.empty) - val params = getCaseClassParams[T]() - val fieldNames = params.map(_.name.decodedName.toString) + val params = getCaseClassParams[T]() + val fieldNames = params.map(_.name.decodedName.toString) val fields = checkCaseClassZipAll[T](innerFuncTermName).map { idxType => - val idx = idxType._1._1 - val columnValues = idxType._1._2 - val fieldTypeName = TypeName(idxType._2.typeSymbol.name.decodedName.toString) + val idx = idxType._1._1 + val columnValues = idxType._1._2 + val fieldTypeName = TypeName(idxType._2.typeSymbol.name.decodedName.toString) val customFunction = () => q"${TermName(builderFunctionPrefix + fieldNames(idx))}.apply($columnValues)" idxType._2 match { case tp if tp <:< typeOf[List[_]] => diff --git a/smt-csv-core/src/main/scala/org/bitlap/csv/core/macros/DeriveToCaseClass.scala b/smt-csv-core/src/main/scala/org/bitlap/csv/core/macros/DeriveToCaseClass.scala index 6c38a36667c25583bc3a840c66a87d16d6116ff0..59b61f98262ee8770bb8f20d5785d1ae0ddaf337 100644 --- a/smt-csv-core/src/main/scala/org/bitlap/csv/core/macros/DeriveToCaseClass.scala +++ b/smt-csv-core/src/main/scala/org/bitlap/csv/core/macros/DeriveToCaseClass.scala @@ -23,9 +23,9 @@ package org.bitlap.csv.core.macros import scala.reflect.macros.blackbox -/** - * @author 梦境迷离 - * @version 1.0,2022/4/29 +/** @author + * 梦境迷离 + * @version 1.0,2022/4/29 */ object DeriveToCaseClass { @@ -37,7 +37,7 @@ object DeriveToCaseClass { // scalafmt: { maxColumn = 400 } def macroImpl[T <: Product: c.WeakTypeTag](line: c.Expr[String], columnSeparator: c.Expr[Char]): c.Expr[Option[T]] = { - val clazzName = c.weakTypeOf[T].typeSymbol.name + val clazzName = c.weakTypeOf[T].typeSymbol.name val innerFuncTermName = TermName("_columns") val fields = (columnsFunc: TermName) => checkCaseClassZipAll[T](columnsFunc).map { idxType => diff --git a/smt-csv-core/src/main/scala/org/bitlap/csv/core/macros/DeriveToString.scala b/smt-csv-core/src/main/scala/org/bitlap/csv/core/macros/DeriveToString.scala index f65271e83785f2d974705634a6d44f16946f9d97..e3a32e6fd98666eb2caeb1abafe64cf5fd6171d0 100644 --- a/smt-csv-core/src/main/scala/org/bitlap/csv/core/macros/DeriveToString.scala +++ b/smt-csv-core/src/main/scala/org/bitlap/csv/core/macros/DeriveToString.scala @@ -23,9 +23,9 @@ package org.bitlap.csv.core.macros import scala.reflect.macros.blackbox -/** - * @author 梦境迷离 - * @version 1.0,2022/4/29 +/** @author + * 梦境迷离 + * @version 1.0,2022/4/29 */ object DeriveToString { @@ -37,9 +37,9 @@ object DeriveToString { def macroImpl[T: c.WeakTypeTag](t: c.Expr[T], columnSeparator: c.Expr[Char]): c.Expr[String] = { val (names, indexTypes) = super.checkCaseClassZip[T] - val clazzName = c.weakTypeOf[T].typeSymbol.name - val innerVarTermName = TermName("_t") - val indexByName = (i: Int) => TermName(names(i)) + val clazzName = c.weakTypeOf[T].typeSymbol.name + val innerVarTermName = TermName("_t") + val indexByName = (i: Int) => TermName(names(i)) val fieldsToString = indexTypes.map { idxType => if (idxType._2 <:< typeOf[Option[_]]) { val genericType = c.typecheck(q"${idxType._2}", c.TYPEmode).tpe.typeArgs.head diff --git a/smt-csv-core/src/main/scala/org/bitlap/csv/core/macros/MacroCache.scala b/smt-csv-core/src/main/scala/org/bitlap/csv/core/macros/MacroCache.scala index 1cda5b9b34b0b1062e7edfbc84dc93d2ec8605ff..aeca52c8d0da90e5346d5eae4943a56fdb4f1326 100644 --- a/smt-csv-core/src/main/scala/org/bitlap/csv/core/macros/MacroCache.scala +++ b/smt-csv-core/src/main/scala/org/bitlap/csv/core/macros/MacroCache.scala @@ -22,13 +22,13 @@ package org.bitlap.csv.core.macros import scala.collection.mutable -/** - * @author 梦境迷离 - * @version 1.0,2022/5/1 +/** @author + * 梦境迷离 + * @version 1.0,2022/5/1 */ object MacroCache { - private var builderCount = 0 + private var builderCount = 0 private var identityCount = 0 def getBuilderId: Int = builderCount.synchronized { diff --git a/smt-csv-core/src/test/scala/org/bitlap/csv/core/test/CsvConverterTest.scala b/smt-csv-core/src/test/scala/org/bitlap/csv/core/test/CsvConverterTest.scala index 427123e012ae64f3a8f67d0f97c362a1350f5aa2..5504839fa5d95b8a683c5097762123b66b97c4c8 100644 --- a/smt-csv-core/src/test/scala/org/bitlap/csv/core/test/CsvConverterTest.scala +++ b/smt-csv-core/src/test/scala/org/bitlap/csv/core/test/CsvConverterTest.scala @@ -25,14 +25,14 @@ import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.bitlap.csv.core.Converter -/** - * @author 梦境迷离 - * @version 1.0,2022/4/29 +/** @author + * 梦境迷离 + * @version 1.0,2022/4/29 */ class CsvConverterTest extends AnyFlatSpec with Matchers { "CsvConverter1" should "ok" in { - val line = "abc,cdf,d,12,2,false,0.1,0.23333" + val line = "abc,cdf,d,12,2,false,0.1,0.23333" val dimension = Converter[Dimension].toScala(line) assert(dimension.toString == "Some(Dimension(abc,Some(cdf),d,12,2,false,0.1,0.23333))") val csv = Converter[Dimension].toCsvString(dimension.orNull) @@ -90,7 +90,7 @@ class CsvConverterTest extends AnyFlatSpec with Matchers { } "CsvConverter6" should "ok when using json value" in { - val line = """abc,"{""a"":""b"",""c"":""d""}",d,12,2,false,0.1,0.23333""" + val line = """abc,"{""a"":""b"",""c"":""d""}",d,12,2,false,0.1,0.23333""" val dimension = Converter[Dimension].toScala(line) println(dimension) assert(dimension.toString == "Some(Dimension(abc,Some({\"a\":\"b\",\"c\":\"d\"}),d,12,2,false,0.1,0.23333))") diff --git a/smt-csv-core/src/test/scala/org/bitlap/csv/core/test/CsvableAndScalableTest.scala b/smt-csv-core/src/test/scala/org/bitlap/csv/core/test/CsvableAndScalableTest.scala index 247a473b27cf715f6844c52efde5158483cc7445..4235fd04c9e2428e5b50265a7ed624a081c3c0c8 100644 --- a/smt-csv-core/src/test/scala/org/bitlap/csv/core/test/CsvableAndScalableTest.scala +++ b/smt-csv-core/src/test/scala/org/bitlap/csv/core/test/CsvableAndScalableTest.scala @@ -30,11 +30,11 @@ import org.bitlap.csv.core.CsvableBuilder import org.bitlap.csv.core.ScalableHelper import java.io.File -/** - * Complex use of common tests +/** Complex use of common tests * - * @author 梦境迷离 - * @version 1.0,2022/5/1 + * @author + * 梦境迷离 + * @version 1.0,2022/5/1 */ class CsvableAndScalableTest extends AnyFlatSpec with Matchers { @@ -199,15 +199,14 @@ class CsvableAndScalableTest extends AnyFlatSpec with Matchers { "CsvableAndScalable7" should "ok macro expose code" in { // to scala - lazy val _ScalableBuilderFunction$dimensions: String => List[org.bitlap.csv.core.test.Dimension3] = ( + lazy val _ScalableBuilderFunction$dimensions: String => List[org.bitlap.csv.core.test.Dimension3] = (dims: String) => org.bitlap.csv.core.StringUtils.extractJsonValues[org.bitlap.csv.core.test.Dimension3](dims)( - ((k: String, v: String) => Dimension3.apply(k, v)) - ) - ); + (k: String, v: String) => Dimension3.apply(k, v) + ); object _ScalaAnno$1 extends _root_.org.bitlap.csv.core.Scalable[Metric2] { - var _line: String = _; - private val _columns = (() => _root_.org.bitlap.csv.core.StringUtils.splitColumns(_ScalaAnno$1._line, ',')); + var _line: String = _; + private val _columns = () => _root_.org.bitlap.csv.core.StringUtils.splitColumns(_ScalaAnno$1._line, ','); override def _toScala(column: String): Option[Metric2] = Option( Metric2( @@ -225,30 +224,26 @@ class CsvableAndScalableTest extends AnyFlatSpec with Matchers { val metrics = scala.Predef .wrapRefArray[String](CsvableAndScalableTest.this.csvData.split("\n")) .toList - .map(((_l: String) => { + .map { (_l: String) => _scalableInstance._line = _l; _scalableInstance._toScala(_l) - })) + } metrics.foreach(println) // to csv - lazy val _CsvableBuilderFunction$dimensions: Seq[org.bitlap.csv.core.test.Dimension3] => String = ( + lazy val _CsvableBuilderFunction$dimensions: Seq[org.bitlap.csv.core.test.Dimension3] => String = (ds: Seq[org.bitlap.csv.core.test.Dimension3]) => - ("\"{" + "\"{" .+( - ds.map[String]( - ( - (kv: org.bitlap.csv.core.test.Dimension3) => - ("\"\"".+(kv.key).+("\"\":\"\"").+(kv.value).+("\"\""): String) - ) + ds.map[String]((kv: org.bitlap.csv.core.test.Dimension3) => + "\"\"".+(kv.key).+("\"\":\"\"").+(kv.value).+("\"\""): String ).mkString(",") ) - .+("}\""): String) - ); + .+("}\""): String; object _CsvAnno$2 extends _root_.org.bitlap.csv.core.Csvable[Metric2] { var _tt: Metric2 = _; - lazy private val toCsv = ((temp: Metric2) => { + lazy private val toCsv = (temp: Metric2) => { val fields = Metric2.unapply(temp).orNull; if (null.$eq$eq(fields)) "" @@ -262,18 +257,18 @@ class CsvableAndScalableTest extends AnyFlatSpec with Matchers { _root_.org.bitlap.csv.core.Csvable[Int]._toCsvString(temp.metricValue) ) .mkString(','.toString) - }); + }; override def _toCsvString(t: Metric2): String = toCsv(_CsvAnno$2._tt) }; lazy val _csvableInstance = _CsvAnno$2; val csv = metrics - .filter(((x$3: Option[org.bitlap.csv.core.test.Metric2]) => x$3.isDefined)) - .map[org.bitlap.csv.core.test.Metric2](((x$4: Option[org.bitlap.csv.core.test.Metric2]) => x$4.get)) - .map(((_t: Metric2) => { + .filter((x$3: Option[org.bitlap.csv.core.test.Metric2]) => x$3.isDefined) + .map[org.bitlap.csv.core.test.Metric2]((x$4: Option[org.bitlap.csv.core.test.Metric2]) => x$4.get) + .map { (_t: Metric2) => _csvableInstance._tt = _t; _csvableInstance._toCsvString(_t) - })) + } .mkString("\n") println(csv) diff --git a/smt-csv-core/src/test/scala/org/bitlap/csv/core/test/CustomConverterBuilderTest.scala b/smt-csv-core/src/test/scala/org/bitlap/csv/core/test/CustomConverterBuilderTest.scala index 5b09041eb2e8ca1f7f2b12d2e59d10c9e3e9e904..18e2e5486f11a8cdce6dfd8a69bca698532862d7 100644 --- a/smt-csv-core/src/test/scala/org/bitlap/csv/core/test/CustomConverterBuilderTest.scala +++ b/smt-csv-core/src/test/scala/org/bitlap/csv/core/test/CustomConverterBuilderTest.scala @@ -25,14 +25,14 @@ import org.bitlap.csv.core.{ CsvableBuilder, ScalableBuilder } import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers -/** - * @author 梦境迷离 - * @version 1.0,2022/4/29 +/** @author + * 梦境迷离 + * @version 1.0,2022/4/29 */ class CustomConverterBuilderTest extends AnyFlatSpec with Matchers { "CustomConverterBuilder1" should "ok" in { - val line = "abc,cdf,d,12,2,false,0.1,0.23333" + val line = "abc,cdf,d,12,2,false,0.1,0.23333" val dimension = ScalableBuilder[Dimension2].convert(line, ',') assert(dimension.toString == "Some(Dimension2(abc,Some(cdf),d,12,2,false,0.1,0.23333))") val csv = CsvableBuilder[Dimension2].convert(dimension.get, ',') @@ -103,7 +103,7 @@ class CustomConverterBuilderTest extends AnyFlatSpec with Matchers { val dimension1 = es.map(e => CsvableBuilder[Dimension2].convert(e, ',')) assert(dimension1 == List("1,hello,c,1,1,true,0.1,0.2", "2,hello bitlap,c,1,1,false,0.1,0.2")) - val csv = List("1,hello,c,1,1,true,0.1,0.2", "2,hello bitlap,c,1,1,false,0.1,0.2") + val csv = List("1,hello,c,1,1,true,0.1,0.2", "2,hello bitlap,c,1,1,false,0.1,0.2") val scala = csv.map(f => ScalableBuilder[Dimension2].convert(f, ',')) assert( scala.toString() == "List(Some(Dimension2(1,Some(hello),c,1,1,true,0.1,0.2)), Some(Dimension2(2,Some(hello bitlap),c,1,1,false,0.1,0.2)))" @@ -111,8 +111,8 @@ class CustomConverterBuilderTest extends AnyFlatSpec with Matchers { } - private val csv = """100,1,"{""city"":""北京"",""os"":""Mac""}",vv,1""" - private val metric = Metric(1, 2, Nil, "name", 2) + private val csv = """100,1,"{""city"":""北京"",""os"":""Mac""}",vv,1""" + private val metric = Metric(1, 2, Nil, "name", 2) private val metric2 = Metric2(1, 2, Nil, "name", 2) "CustomConverterBuilder6" should "fail when find List or Seq but without using setFiled" in { @@ -137,7 +137,7 @@ class CustomConverterBuilderTest extends AnyFlatSpec with Matchers { } "CustomConverterBuilder8" should "ok when not pass columnSeparator" in { - val e = Dimension2("1", Some("hello"), 'c', 1L, 1, false, 0.1f, 0.2) + val e = Dimension2("1", Some("hello"), 'c', 1L, 1, false, 0.1f, 0.2) val csv = CsvableBuilder[Dimension2].convert(e) println(csv) assert(csv == "1,hello,c,1,1,false,0.1,0.2") diff --git a/smt-csv-core/src/test/scala/org/bitlap/csv/core/test/Dimension.scala b/smt-csv-core/src/test/scala/org/bitlap/csv/core/test/Dimension.scala index 9bdff5602417bd32bd3ec0e7680a9e4a44703c33..f5dd38f5def473e743355d4650d29e8be2d5a530 100644 --- a/smt-csv-core/src/test/scala/org/bitlap/csv/core/test/Dimension.scala +++ b/smt-csv-core/src/test/scala/org/bitlap/csv/core/test/Dimension.scala @@ -24,9 +24,9 @@ package org.bitlap.csv.core.test import org.bitlap.csv.core.Converter import org.bitlap.csv.core.macros.{ DeriveToCaseClass, DeriveToString } -/** - * @author 梦境迷离 - * @version 1.0,2022/4/29 +/** @author + * 梦境迷离 + * @version 1.0,2022/4/29 */ case class Dimension(key: String, value: Option[String], d: Char, c: Long, e: Short, f: Boolean, g: Float, h: Double) diff --git a/smt-csv-core/src/test/scala/org/bitlap/csv/core/test/StringUtilsTest.scala b/smt-csv-core/src/test/scala/org/bitlap/csv/core/test/StringUtilsTest.scala index bef61c597bd2e2ce89a8197dc643985b4c94819d..8c3c57f0f2fd39f8eae6ed67b3b131509287708c 100644 --- a/smt-csv-core/src/test/scala/org/bitlap/csv/core/test/StringUtilsTest.scala +++ b/smt-csv-core/src/test/scala/org/bitlap/csv/core/test/StringUtilsTest.scala @@ -28,15 +28,15 @@ import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import java.io.{ BufferedReader, InputStreamReader } -/** - * @author 梦境迷离 - * @version 1.0,2022/4/30 +/** @author + * 梦境迷离 + * @version 1.0,2022/4/30 */ class StringUtilsTest extends AnyFlatSpec with Matchers { "StringUtilsTest1" should "ok" in { val line = """abc,"{""a"":""b"",""c"":""d""}",d,12,2,false,0.1,0.23333""" - val csv = StringUtils.splitColumns(line, ',') + val csv = StringUtils.splitColumns(line, ',') println(csv) assert(csv.size == 8) } @@ -44,13 +44,13 @@ class StringUtilsTest extends AnyFlatSpec with Matchers { "StringUtilsTest2" should "ok" in { // only extract json `"{""a"":""b"",""c"":""d""}"` val line = """abc,"{""a"":""b"",""c"":""d""}",d,12,2,false,0.1,0.23333""" - val csv = StringUtils.extractJsonValues[Dimension3](line)((k, v) => Dimension3(k, v)) + val csv = StringUtils.extractJsonValues[Dimension3](line)((k, v) => Dimension3(k, v)) println(csv) assert(csv.toString() == "List(Dimension3(\"a\",\"b\"), Dimension3(\"c\",\"d\"))") } "StringUtilsTest3" should "ok for file" in { - val reader = new InputStreamReader(ClassLoader.getSystemResourceAsStream("simple_data.csv")) + val reader = new InputStreamReader(ClassLoader.getSystemResourceAsStream("simple_data.csv")) val bufferedReader = new BufferedReader(reader) FileUtils.using(bufferedReader) { input => var line: String = null diff --git a/smt-csv-derive/src/main/scala/org/bitlap/csv/derive/DeriveCsvConverter.scala b/smt-csv-derive/src/main/scala/org/bitlap/csv/derive/DeriveCsvConverter.scala index 4d880cb9eb78ce898ad0302486d128739bcce08f..fe0d5ff172b52ab4189b8321eb594b790312dd7b 100644 --- a/smt-csv-derive/src/main/scala/org/bitlap/csv/derive/DeriveCsvConverter.scala +++ b/smt-csv-derive/src/main/scala/org/bitlap/csv/derive/DeriveCsvConverter.scala @@ -26,11 +26,11 @@ import org.bitlap.csv.core.macros.AbstractMacroProcessor import scala.reflect.macros.blackbox -/** - * This is a tool macro for automatic derivation of the base CSV converter. +/** This is a tool macro for automatic derivation of the base CSV converter. * - * @author 梦境迷离 - * @version 1.0,2022/4/29 + * @author + * 梦境迷离 + * @version 1.0,2022/4/29 */ object DeriveCsvConverter { @@ -43,7 +43,7 @@ object DeriveCsvConverter { def macroImplWithColumnSeparator[CC: c.WeakTypeTag](columnSeparator: c.Expr[Char]): c.Expr[CC] = { import c.universe._ val clazzName = c.weakTypeOf[CC].typeSymbol.name - val typeName = TypeName(clazzName.decodedName.toString) + val typeName = TypeName(clazzName.decodedName.toString) val tree = q""" new Converter[$typeName] { diff --git a/smt-csv-derive/src/test/scala/org/bitlap/csv/derive/test/CsvLine.scala b/smt-csv-derive/src/test/scala/org/bitlap/csv/derive/test/CsvLine.scala index 1772899d09426b74b0c9cfe83ff30a136d56884b..cf2424ac2b5308460c61b94b5224f25936ee0fa6 100644 --- a/smt-csv-derive/src/test/scala/org/bitlap/csv/derive/test/CsvLine.scala +++ b/smt-csv-derive/src/test/scala/org/bitlap/csv/derive/test/CsvLine.scala @@ -24,9 +24,9 @@ package org.bitlap.csv.derive.test import org.bitlap.csv.core.Converter import org.bitlap.csv.derive.DeriveCsvConverter -/** - * @author 梦境迷离 - * @version 1.0,2022/4/29 +/** @author + * 梦境迷离 + * @version 1.0,2022/4/29 */ case class CsvLine(key: String, value: Option[String], d: Char, c: Long, e: Short, f: Boolean, g: Float, h: Double) diff --git a/smt-csv-derive/src/test/scala/org/bitlap/csv/derive/test/CsvLine2.scala b/smt-csv-derive/src/test/scala/org/bitlap/csv/derive/test/CsvLine2.scala index 526083fb07b5421137330d02642ce08217fb0310..fb44f12badbbc8a04172360c5d89b3f129614f19 100644 --- a/smt-csv-derive/src/test/scala/org/bitlap/csv/derive/test/CsvLine2.scala +++ b/smt-csv-derive/src/test/scala/org/bitlap/csv/derive/test/CsvLine2.scala @@ -24,9 +24,9 @@ package org.bitlap.csv.derive.test import org.bitlap.csv.core.Converter import org.bitlap.csv.derive.DeriveCsvConverter -/** - * @author 梦境迷离 - * @version 1.0,2022/4/29 +/** @author + * 梦境迷离 + * @version 1.0,2022/4/29 */ case class CsvLine2(key: String, value: Option[String]) diff --git a/smt-csv-derive/src/test/scala/org/bitlap/csv/derive/test/CsvLine3.scala b/smt-csv-derive/src/test/scala/org/bitlap/csv/derive/test/CsvLine3.scala index 02cb7b79825ed7143fc4fb24b36816e0a94104d6..752db7cdae9effc55ea75150ff0850479fc37619 100644 --- a/smt-csv-derive/src/test/scala/org/bitlap/csv/derive/test/CsvLine3.scala +++ b/smt-csv-derive/src/test/scala/org/bitlap/csv/derive/test/CsvLine3.scala @@ -27,9 +27,9 @@ import org.bitlap.csv.derive.DeriveCsvConverter import java.time.LocalDateTime import java.time.format.DateTimeFormatter -/** - * @author 梦境迷离 - * @version 1.0,2022/4/29 +/** @author + * 梦境迷离 + * @version 1.0,2022/4/29 */ case class CsvLine3(key: String, time: LocalDateTime) diff --git a/smt-csv-derive/src/test/scala/org/bitlap/csv/derive/test/CsvLine4.scala b/smt-csv-derive/src/test/scala/org/bitlap/csv/derive/test/CsvLine4.scala index a3bc374cf1a296bb46942a0c924805db7f6725a4..7ee2095f585c4f5e73bb2e53fd904d7090ce3bce 100644 --- a/smt-csv-derive/src/test/scala/org/bitlap/csv/derive/test/CsvLine4.scala +++ b/smt-csv-derive/src/test/scala/org/bitlap/csv/derive/test/CsvLine4.scala @@ -24,9 +24,9 @@ package org.bitlap.csv.derive.test import org.bitlap.csv.core.{ Converter, StringUtils } import org.bitlap.csv.derive.DeriveCsvConverter -/** - * @author 梦境迷离 - * @version 1.0,2022/5/15 +/** @author + * 梦境迷离 + * @version 1.0,2022/5/15 */ case class CsvLine4(time: Long, entity: Int, dimensions: List[Dimension], metricName: String, metricValue: Int) diff --git a/smt-csv-derive/src/test/scala/org/bitlap/csv/derive/test/DeriveCsvConverterTest.scala b/smt-csv-derive/src/test/scala/org/bitlap/csv/derive/test/DeriveCsvConverterTest.scala index d3373c822e4f44dcd7e68c6f235819116818f013..900055c2a866bf72a3216ad0e3695840c0536d09 100644 --- a/smt-csv-derive/src/test/scala/org/bitlap/csv/derive/test/DeriveCsvConverterTest.scala +++ b/smt-csv-derive/src/test/scala/org/bitlap/csv/derive/test/DeriveCsvConverterTest.scala @@ -25,9 +25,9 @@ import org.bitlap.csv.core.Converter import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers -/** - * @author 梦境迷离 - * @version 1.0,2022/4/29 +/** @author + * 梦境迷离 + * @version 1.0,2022/4/29 */ class DeriveCsvConverterTest extends AnyFlatSpec with Matchers { @@ -50,7 +50,7 @@ class DeriveCsvConverterTest extends AnyFlatSpec with Matchers { |200,3,"{""city"":""北京"",""os"":""Mac""}",pv,2""".stripMargin "DeriveCsvConverter1" should "ok" in { - val line = "abc,cdf,d,12,2,false,0.1,0.23333" + val line = "abc,cdf,d,12,2,false,0.1,0.23333" val dimension = Converter[CsvLine].toScala(line) assert(dimension.toString == "Some(CsvLine(abc,Some(cdf),d,12,2,false,0.1,0.23333))") val csv = Converter[CsvLine].toCsvString(dimension.orNull) diff --git a/smt-tools/src/main/scala/org/bitlap/tools/LogLevel.scala b/smt-tools/src/main/scala/org/bitlap/tools/LogLevel.scala index 8b304ad2d2e76e1a0a3cc28ee5a692520aac2a5a..840063df3c27ff18a1a7313ae3dd50792e9e8cee 100644 --- a/smt-tools/src/main/scala/org/bitlap/tools/LogLevel.scala +++ b/smt-tools/src/main/scala/org/bitlap/tools/LogLevel.scala @@ -21,12 +21,12 @@ package org.bitlap.tools -/** - * Log Level for elapsed +/** Log Level for elapsed * - * @author 梦境迷离 - * @since 2021/8/7 - * @version 1.0 + * @author + * 梦境迷离 + * @since 2021/8/7 + * @version 1.0 */ object LogLevel extends Enumeration { @@ -35,7 +35,7 @@ object LogLevel extends Enumeration { private[bitlap] def getLogLevel(shortType: String): LogLevel = { // TODO not good way - val tpe1 = s"$PACKAGE.elapsed.$shortType" //LogLevel.INFO + val tpe1 = s"$PACKAGE.elapsed.$shortType" // LogLevel.INFO val tpe2 = s"$PACKAGE.elapsed.LogLevel.$shortType" // INFO val v = LogLevel.values.find { p => s"$PACKAGE.elapsed.LogLevel.${p.toString}" == tpe1 || diff --git a/smt-tools/src/main/scala/org/bitlap/tools/apply.scala b/smt-tools/src/main/scala/org/bitlap/tools/apply.scala index 07c27cc03071387d3d9e430df79c7863b0be3d9a..c7ab3a7ee714701efc2b76619a809602f6202eb7 100644 --- a/smt-tools/src/main/scala/org/bitlap/tools/apply.scala +++ b/smt-tools/src/main/scala/org/bitlap/tools/apply.scala @@ -25,12 +25,12 @@ import org.bitlap.tools.macros.applyMacro import scala.annotation.{ compileTimeOnly, StaticAnnotation } -/** - * annotation to generate apply method for primary construction of ordinary classes. +/** annotation to generate apply method for primary construction of ordinary classes. * - * @author 梦境迷离 - * @since 2021/6/30 - * @version 1.0 + * @author + * 梦境迷离 + * @since 2021/6/30 + * @version 1.0 */ @compileTimeOnly("enable macro to expand macro annotations") final class apply extends StaticAnnotation { diff --git a/smt-tools/src/main/scala/org/bitlap/tools/builder.scala b/smt-tools/src/main/scala/org/bitlap/tools/builder.scala index ef9a7b2747ae9a7d9b28f70d10db911b7876908c..9d051fd33e9c66a98a90a34bad8cd8ec0e8aafbb 100644 --- a/smt-tools/src/main/scala/org/bitlap/tools/builder.scala +++ b/smt-tools/src/main/scala/org/bitlap/tools/builder.scala @@ -25,12 +25,12 @@ import org.bitlap.tools.macros.builderMacro import scala.annotation.{ compileTimeOnly, StaticAnnotation } -/** - * annotation to generate builder pattern for classes. +/** annotation to generate builder pattern for classes. * - * @author 梦境迷离 - * @since 2021/6/19 - * @version 1.0 + * @author + * 梦境迷离 + * @since 2021/6/19 + * @version 1.0 */ @compileTimeOnly("enable macro to expand macro annotations") final class builder extends StaticAnnotation { diff --git a/smt-tools/src/main/scala/org/bitlap/tools/constructor.scala b/smt-tools/src/main/scala/org/bitlap/tools/constructor.scala index 5b53f9c993223b5549ab4122f6c0679656f59493..2c51b5e4b895396c925dc421867d527905e33b05 100644 --- a/smt-tools/src/main/scala/org/bitlap/tools/constructor.scala +++ b/smt-tools/src/main/scala/org/bitlap/tools/constructor.scala @@ -25,13 +25,14 @@ import org.bitlap.tools.macros.constructorMacro import scala.annotation.{ compileTimeOnly, StaticAnnotation } -/** - * annotation to generate secondary constructor method for classes. +/** annotation to generate secondary constructor method for classes. * - * @author 梦境迷离 - * @param excludeFields Whether to exclude the specified var fields. - * @since 2021/7/3 - * @version 1.0 + * @author + * 梦境迷离 + * @param excludeFields + * Whether to exclude the specified var fields. + * @since 2021/7/3 + * @version 1.0 */ @compileTimeOnly("enable macro to expand macro annotations") final class constructor(excludeFields: Seq[String] = Nil) extends StaticAnnotation { diff --git a/smt-tools/src/main/scala/org/bitlap/tools/elapsed.scala b/smt-tools/src/main/scala/org/bitlap/tools/elapsed.scala index da11e13b5ab9e44050495572ec1019dbc4341b05..89c466e85ac4b2341b105b41408699dffd3db13c 100644 --- a/smt-tools/src/main/scala/org/bitlap/tools/elapsed.scala +++ b/smt-tools/src/main/scala/org/bitlap/tools/elapsed.scala @@ -27,14 +27,16 @@ import org.bitlap.tools.macros.elapsedMacro.ElapsedProcessor import scala.annotation.{ compileTimeOnly, StaticAnnotation } import scala.concurrent.duration.Duration -/** - * annotation to record method cost time. +/** annotation to record method cost time. * - * @author 梦境迷离 - * @param limit Time consuming condition to trigger log. - * @param logLevel Log Level. - * @since 2021/8/7 - * @version 1.0 + * @author + * 梦境迷离 + * @param limit + * Time consuming condition to trigger log. + * @param logLevel + * Log Level. + * @since 2021/8/7 + * @version 1.0 */ @compileTimeOnly("enable macro to expand macro annotations") final class elapsed(limit: Duration, logLevel: LogLevel) extends StaticAnnotation { diff --git a/smt-tools/src/main/scala/org/bitlap/tools/equalsAndHashCode.scala b/smt-tools/src/main/scala/org/bitlap/tools/equalsAndHashCode.scala index 28d0d5a1b33e67cf25017b84fef7b9a9ed704237..ca5f96cf5cc5b5fbad12d8807b75d25dd939555b 100644 --- a/smt-tools/src/main/scala/org/bitlap/tools/equalsAndHashCode.scala +++ b/smt-tools/src/main/scala/org/bitlap/tools/equalsAndHashCode.scala @@ -25,13 +25,14 @@ import org.bitlap.tools.macros.equalsAndHashCodeMacro.EqualsAndHashCodeProcessor import scala.annotation.{ compileTimeOnly, StaticAnnotation } -/** - * annotation to generate equals and hashcode method for classes. +/** annotation to generate equals and hashcode method for classes. * - * @author 梦境迷离 - * @param excludeFields Whether to exclude the specified internal fields. - * @since 2021/7/18 - * @version 1.0 + * @author + * 梦境迷离 + * @param excludeFields + * Whether to exclude the specified internal fields. + * @since 2021/7/18 + * @version 1.0 */ @compileTimeOnly("enable macro to expand macro annotations") final class equalsAndHashCode(excludeFields: Seq[String] = Nil) extends StaticAnnotation { diff --git a/smt-tools/src/main/scala/org/bitlap/tools/jacksonEnum.scala b/smt-tools/src/main/scala/org/bitlap/tools/jacksonEnum.scala index 512ffce66d880c382090557443cce95f8c32a3bc..d5e5b9c88cfe3f7e72df25a02e4fe047479cdf60 100644 --- a/smt-tools/src/main/scala/org/bitlap/tools/jacksonEnum.scala +++ b/smt-tools/src/main/scala/org/bitlap/tools/jacksonEnum.scala @@ -25,14 +25,16 @@ import org.bitlap.tools.macros.jacksonEnumMacro import scala.annotation.{ compileTimeOnly, StaticAnnotation } -/** - * annotation to generate equals and hashcode method for classes. +/** annotation to generate equals and hashcode method for classes. * - * @author 梦境迷离 - * @author choly - * @param nonTypeRefers Whether to not generate the subclass of the TypeReference for paramTypes of class. - * @since 2021/8/3 - * @version 1.0 + * @author + * 梦境迷离 + * @author + * choly + * @param nonTypeRefers + * Whether to not generate the subclass of the TypeReference for paramTypes of class. + * @since 2021/8/3 + * @version 1.0 */ @compileTimeOnly("enable macro to expand macro annotations") final class jacksonEnum(nonTypeRefers: Seq[String] = Nil) extends StaticAnnotation { diff --git a/smt-tools/src/main/scala/org/bitlap/tools/javaCompatible.scala b/smt-tools/src/main/scala/org/bitlap/tools/javaCompatible.scala index 8fef1e38ad27e608594e59e90c9f0a386463509e..4efc93a1743b78801b704684f81fd84fa04d0cc5 100644 --- a/smt-tools/src/main/scala/org/bitlap/tools/javaCompatible.scala +++ b/smt-tools/src/main/scala/org/bitlap/tools/javaCompatible.scala @@ -24,13 +24,13 @@ package org.bitlap.tools import scala.annotation.{ compileTimeOnly, StaticAnnotation } import org.bitlap.tools.macros.javaCompatibleMacro -/** - * annotation to generate non-parameter constructor and get/set method for case classes. - * Fields marked `private[this]` in curry are not supported ! +/** annotation to generate non-parameter constructor and get/set method for case classes. Fields marked `private[this]` + * in curry are not supported ! * - * @author 梦境迷离 - * @since 2021/11/23 - * @version 1.0 + * @author + * 梦境迷离 + * @since 2021/11/23 + * @version 1.0 */ @compileTimeOnly("enable macro to expand macro annotations") final class javaCompatible extends StaticAnnotation { diff --git a/smt-tools/src/main/scala/org/bitlap/tools/json.scala b/smt-tools/src/main/scala/org/bitlap/tools/json.scala index dc0713e618f3e9e6bcc9c564d6433d98f6a31f01..a5b9243fd9a218c28f83143507f6b632f461db99 100644 --- a/smt-tools/src/main/scala/org/bitlap/tools/json.scala +++ b/smt-tools/src/main/scala/org/bitlap/tools/json.scala @@ -25,12 +25,12 @@ import org.bitlap.tools.macros.jsonMacro import scala.annotation.{ compileTimeOnly, StaticAnnotation } -/** - * annotation to generate play-json implicit object for case classes. +/** annotation to generate play-json implicit object for case classes. * - * @author 梦境迷离 - * @since 2021/6/13 - * @version 1.0 + * @author + * 梦境迷离 + * @since 2021/6/13 + * @version 1.0 */ @compileTimeOnly("enable macro to expand macro annotations") final class json extends StaticAnnotation { diff --git a/smt-tools/src/main/scala/org/bitlap/tools/log.scala b/smt-tools/src/main/scala/org/bitlap/tools/log.scala index fc6bf3f618fda015017f5e6c25f12010322252f5..b395d288d5ab66f7c5338b400a2680d5df2aefe0 100644 --- a/smt-tools/src/main/scala/org/bitlap/tools/log.scala +++ b/smt-tools/src/main/scala/org/bitlap/tools/log.scala @@ -26,13 +26,14 @@ import org.bitlap.tools.macros.logMacro import scala.annotation.{ compileTimeOnly, StaticAnnotation } -/** - * annotation to generate log. +/** annotation to generate log. * - * @author 梦境迷离 - * @param logType Specifies the type of `log` that needs to be generated - * @since 2021/6/28 - * @version 1.0 + * @author + * 梦境迷离 + * @param logType + * Specifies the type of `log` that needs to be generated + * @since 2021/6/28 + * @version 1.0 */ @compileTimeOnly("enable macro to expand macro annotations") final class log(logType: LogType.LogType = LogType.JLog) extends StaticAnnotation { diff --git a/smt-tools/src/main/scala/org/bitlap/tools/logs/LogType.scala b/smt-tools/src/main/scala/org/bitlap/tools/logs/LogType.scala index f4ba1ad92827249297b374264cb88ea6e6623096..1a04149c46893f88a547291eb60d17cc23dd9cff 100644 --- a/smt-tools/src/main/scala/org/bitlap/tools/logs/LogType.scala +++ b/smt-tools/src/main/scala/org/bitlap/tools/logs/LogType.scala @@ -25,9 +25,9 @@ import org.bitlap.tools.PACKAGE import org.bitlap.tools.logs.extension.{ ScalaLoggingLazyImpl, ScalaLoggingStrictImpl } import org.bitlap.tools.logs.impl.{ JLogImpl, Log4J2Impl, Slf4jImpl } -/** - * @author 梦境迷离 - * @version 1.0,2022/3/29 +/** @author + * 梦境迷离 + * @version 1.0,2022/3/29 */ object LogType extends Enumeration { @@ -35,11 +35,11 @@ object LogType extends Enumeration { val JLog, Log4j2, Slf4j, ScalaLoggingLazy, ScalaLoggingStrict = Value private lazy val types: Map[LogType, BaseLog] = Map( - JLogImpl.`type` -> JLogImpl, - Log4J2Impl.`type` -> Log4J2Impl, - Slf4jImpl.`type` -> Slf4jImpl, + JLogImpl.`type` -> JLogImpl, + Log4J2Impl.`type` -> Log4J2Impl, + Slf4jImpl.`type` -> Slf4jImpl, ScalaLoggingStrictImpl.`type` -> ScalaLoggingStrictImpl, - ScalaLoggingLazyImpl.`type` -> ScalaLoggingLazyImpl + ScalaLoggingLazyImpl.`type` -> ScalaLoggingLazyImpl ) def getLogImpl(logType: LogType): BaseLog = @@ -47,12 +47,14 @@ object LogType extends Enumeration { // TODO not use Enumeratio def getLogType(shortType: String): LogType = { - val tpe1 = s"$PACKAGE.logs.$shortType" //LogType.JLog + val tpe1 = s"$PACKAGE.logs.$shortType" // LogType.JLog val tpe2 = s"$PACKAGE.logs.LogType.$shortType" // JLog val v = LogType.values.find { p => s"$PACKAGE.logs.LogType.${p.toString}" == tpe1 || s"$PACKAGE.logs.LogType.${p.toString}" == tpe2 || s"$PACKAGE.logs.LogType.${p.toString}" == shortType - }.getOrElse(throw new Exception(s"Not support log type: $shortType")).toString + } + .getOrElse(throw new Exception(s"Not support log type: $shortType")) + .toString LogType.withName(v) } } diff --git a/smt-tools/src/main/scala/org/bitlap/tools/logs/extension/ScalaLazyLogging.scala b/smt-tools/src/main/scala/org/bitlap/tools/logs/extension/ScalaLazyLogging.scala index f7c3a57a7245eb66bb5b951df14e3ba0fce69639..47a88e7ff7fcf1228e3dec829b64bdcb9aff824b 100644 --- a/smt-tools/src/main/scala/org/bitlap/tools/logs/extension/ScalaLazyLogging.scala +++ b/smt-tools/src/main/scala/org/bitlap/tools/logs/extension/ScalaLazyLogging.scala @@ -23,9 +23,8 @@ package org.bitlap.tools.logs.extension import org.slf4j.LoggerFactory -/** - * Defines `logger` as a lazy value initialized with an underlying `org.slf4j.Logger` - * named according to the class into which this trait is mixed. +/** Defines `logger` as a lazy value initialized with an underlying `org.slf4j.Logger` named according to the class into + * which this trait is mixed. */ trait ScalaLazyLogging { diff --git a/smt-tools/src/main/scala/org/bitlap/tools/logs/extension/ScalaLoggingLazyImpl.scala b/smt-tools/src/main/scala/org/bitlap/tools/logs/extension/ScalaLoggingLazyImpl.scala index fd706d36ebcf4bde0709f095eb21edaed7daa697..7f7eccb4d2baa337a68b6c4973993431765d79f8 100644 --- a/smt-tools/src/main/scala/org/bitlap/tools/logs/extension/ScalaLoggingLazyImpl.scala +++ b/smt-tools/src/main/scala/org/bitlap/tools/logs/extension/ScalaLoggingLazyImpl.scala @@ -26,12 +26,12 @@ import org.bitlap.tools.logs.{ BaseLog, LogArgument, LogType } import scala.reflect.macros.whitebox -/** - * scalalogging LazyLogging +/** scalalogging LazyLogging * - * @author 梦境迷离 - * @since 2021/7/26 - * @version 1.0 + * @author + * 梦境迷离 + * @since 2021/7/26 + * @version 1.0 */ object ScalaLoggingLazyImpl extends BaseLog { diff --git a/smt-tools/src/main/scala/org/bitlap/tools/logs/extension/ScalaLoggingStrictImpl.scala b/smt-tools/src/main/scala/org/bitlap/tools/logs/extension/ScalaLoggingStrictImpl.scala index df03396de4fb130a24c84f265e7e4c6b3a96a739..8c9eb406bbc08c915c1e0a9585e2edec176d990d 100644 --- a/smt-tools/src/main/scala/org/bitlap/tools/logs/extension/ScalaLoggingStrictImpl.scala +++ b/smt-tools/src/main/scala/org/bitlap/tools/logs/extension/ScalaLoggingStrictImpl.scala @@ -26,12 +26,12 @@ import org.bitlap.tools.logs.{ BaseLog, LogArgument, LogType } import scala.reflect.macros.whitebox -/** - * * scalalogging StrictLogging +/** * scalalogging StrictLogging * - * @author 梦境迷离 - * @since 2021/7/26 - * @version 1.0 + * @author + * 梦境迷离 + * @since 2021/7/26 + * @version 1.0 */ object ScalaLoggingStrictImpl extends BaseLog { diff --git a/smt-tools/src/main/scala/org/bitlap/tools/logs/extension/ScalaStrictLogging.scala b/smt-tools/src/main/scala/org/bitlap/tools/logs/extension/ScalaStrictLogging.scala index fc073b77bc0fcb39bafa06a1cd72a464f6aa9e54..45afa66332cc3e0af4cf1a14b46ce93e9a3fabc7 100644 --- a/smt-tools/src/main/scala/org/bitlap/tools/logs/extension/ScalaStrictLogging.scala +++ b/smt-tools/src/main/scala/org/bitlap/tools/logs/extension/ScalaStrictLogging.scala @@ -23,9 +23,8 @@ package org.bitlap.tools.logs.extension import org.slf4j.LoggerFactory -/** - * Defines `logger` as a value initialized with an underlying `org.slf4j.Logger` - * named according to the class into which this trait is mixed. +/** Defines `logger` as a value initialized with an underlying `org.slf4j.Logger` named according to the class into + * which this trait is mixed. */ trait ScalaStrictLogging { diff --git a/smt-tools/src/main/scala/org/bitlap/tools/logs/impl/JLogImpl.scala b/smt-tools/src/main/scala/org/bitlap/tools/logs/impl/JLogImpl.scala index 50ad40693d2f683a961158fcadd2c797dbb4b989..89bdbb3fbad021b25ce76751133d0eac8898a64e 100644 --- a/smt-tools/src/main/scala/org/bitlap/tools/logs/impl/JLogImpl.scala +++ b/smt-tools/src/main/scala/org/bitlap/tools/logs/impl/JLogImpl.scala @@ -26,9 +26,9 @@ import org.bitlap.tools.logs.LogType.LogType import scala.reflect.macros.whitebox -/** - * @author 梦境迷离 - * @version 1.0,2022/3/29 +/** @author + * 梦境迷离 + * @version 1.0,2022/3/29 */ object JLogImpl extends BaseLog { @@ -38,12 +38,12 @@ object JLogImpl extends BaseLog { import c.universe._ if (logArgument.isClass) { q"""@transient private final val log: java.util.logging.Logger = java.util.logging.Logger.getLogger(classOf[${TypeName( - logArgument.classNameStr - )}].getName)""" + logArgument.classNameStr + )}].getName)""" } else { q"""@transient private final val log: java.util.logging.Logger = java.util.logging.Logger.getLogger(${TermName( - logArgument.classNameStr - )}.getClass.getName)""" + logArgument.classNameStr + )}.getClass.getName)""" } } diff --git a/smt-tools/src/main/scala/org/bitlap/tools/logs/impl/Log4J2Impl.scala b/smt-tools/src/main/scala/org/bitlap/tools/logs/impl/Log4J2Impl.scala index db23a0bb01528bb4bb6bbb9a48d4dc5088a3e53e..96070867a9b6b330b85b26b3975f1158b79317b1 100644 --- a/smt-tools/src/main/scala/org/bitlap/tools/logs/impl/Log4J2Impl.scala +++ b/smt-tools/src/main/scala/org/bitlap/tools/logs/impl/Log4J2Impl.scala @@ -26,9 +26,9 @@ import org.bitlap.tools.logs.LogType.LogType import scala.reflect.macros.whitebox -/** - * @author 梦境迷离 - * @version 1.0,2022/3/29 +/** @author + * 梦境迷离 + * @version 1.0,2022/3/29 */ object Log4J2Impl extends BaseLog { @@ -38,12 +38,12 @@ object Log4J2Impl extends BaseLog { import c.universe._ if (logArgument.isClass) { q"""@transient private final val log: org.apache.logging.log4j.Logger = org.apache.logging.log4j.LogManager.getLogger(classOf[${TypeName( - logArgument.classNameStr - )}].getName)""" + logArgument.classNameStr + )}].getName)""" } else { q"""@transient private final val log: org.apache.logging.log4j.Logger = org.apache.logging.log4j.LogManager.getLogger(${TermName( - logArgument.classNameStr - )}.getClass.getName)""" + logArgument.classNameStr + )}.getClass.getName)""" } } diff --git a/smt-tools/src/main/scala/org/bitlap/tools/logs/impl/Slf4jImpl.scala b/smt-tools/src/main/scala/org/bitlap/tools/logs/impl/Slf4jImpl.scala index 518324ecd710ca5c093992e48db46aa575d74ec1..67a3a359f85d6dc185aba7101ea1ed91ad9d5748 100644 --- a/smt-tools/src/main/scala/org/bitlap/tools/logs/impl/Slf4jImpl.scala +++ b/smt-tools/src/main/scala/org/bitlap/tools/logs/impl/Slf4jImpl.scala @@ -26,9 +26,9 @@ import org.bitlap.tools.logs.LogType.LogType import scala.reflect.macros.whitebox -/** - * @author 梦境迷离 - * @version 1.0,2022/3/29 +/** @author + * 梦境迷离 + * @version 1.0,2022/3/29 */ object Slf4jImpl extends BaseLog { @@ -38,12 +38,12 @@ object Slf4jImpl extends BaseLog { import c.universe._ if (logArgument.isClass) { q"""@transient private final val log: org.slf4j.Logger = org.slf4j.LoggerFactory.getLogger(classOf[${TypeName( - logArgument.classNameStr - )}])""" + logArgument.classNameStr + )}])""" } else { q"""@transient private final val log: org.slf4j.Logger = org.slf4j.LoggerFactory.getLogger(${TermName( - logArgument.classNameStr - )}.getClass)""" + logArgument.classNameStr + )}.getClass)""" } } } diff --git a/smt-tools/src/main/scala/org/bitlap/tools/logs/package.scala b/smt-tools/src/main/scala/org/bitlap/tools/logs/package.scala index d428655faa246a775523fea713f15b886e5854e5..67326f1559cbec37092f75a85264d23d7620a5d2 100644 --- a/smt-tools/src/main/scala/org/bitlap/tools/logs/package.scala +++ b/smt-tools/src/main/scala/org/bitlap/tools/logs/package.scala @@ -25,15 +25,15 @@ import org.bitlap.tools.logs.LogType.LogType import scala.reflect.macros.whitebox -/** - * @author 梦境迷离 - * @version 1.0,2022/3/29 +/** @author + * 梦境迷离 + * @version 1.0,2022/3/29 */ package object logs { - /** - * @author 梦境迷离 - * @version 1.0,2022/3/29 + /** @author + * 梦境迷离 + * @version 1.0,2022/3/29 */ private[tools] trait BaseLog { @@ -42,10 +42,12 @@ package object logs { def getTemplate(c: whitebox.Context)(logArgument: LogArgument): c.Tree } - /** - * @author 梦境迷离 - * @param classNameStr The class Name. - * @param isClass Is it a class? + /** @author + * 梦境迷离 + * @param classNameStr + * The class Name. + * @param isClass + * Is it a class? */ private[tools] case class LogArgument(classNameStr: String, isClass: Boolean) diff --git a/smt-tools/src/main/scala/org/bitlap/tools/macros/AbstractMacroProcessor.scala b/smt-tools/src/main/scala/org/bitlap/tools/macros/AbstractMacroProcessor.scala index ccca2e7b4dc519390ba5482fa07c7df55ef6a4dc..6e499623d470834c02bd98f083c1e900dac7f847 100644 --- a/smt-tools/src/main/scala/org/bitlap/tools/macros/AbstractMacroProcessor.scala +++ b/smt-tools/src/main/scala/org/bitlap/tools/macros/AbstractMacroProcessor.scala @@ -26,10 +26,10 @@ import java.time.format.DateTimeFormatter import scala.annotation.tailrec import scala.reflect.macros.whitebox -/** - * @author 梦境迷离 - * @since 2021/7/24 - * @version 1.0 +/** @author + * 梦境迷离 + * @since 2021/7/24 + * @version 1.0 */ abstract class AbstractMacroProcessor(val c: whitebox.Context) { @@ -37,20 +37,21 @@ abstract class AbstractMacroProcessor(val c: whitebox.Context) { protected final lazy val SDKClasses = Set("java.lang.Object", "scala.AnyRef") - /** - * Subclasses should override the method and return the final result abstract syntax tree, or an abstract syntax tree close to the final result. + /** Subclasses should override the method and return the final result abstract syntax tree, or an abstract syntax tree + * close to the final result. * - * @param classDecl - * @param compDeclOpt - * @return `c.Expr[Any]`, Why use Any? The dependent type need aux-pattern in scala2. Now let's get around this. + * @param classDecl + * @param compDeclOpt + * @return + * `c.Expr[Any]`, Why use Any? The dependent type need aux-pattern in scala2. Now let's get around this. */ def createCustomExpr(classDecl: ClassDef, compDeclOpt: Option[ModuleDef] = None): Any = ??? - /** - * Subclasses should override this method if it cannot use [[createCustomExpr]] method. + /** Subclasses should override this method if it cannot use [[createCustomExpr]] method. * - * @param annottees - * @return Return a macro expanded final syntax tree. + * @param annottees + * @return + * Return a macro expanded final syntax tree. */ def impl(annottees: Expr[Any]*): Expr[Any] = { checkAnnottees(annottees) @@ -59,27 +60,24 @@ abstract class AbstractMacroProcessor(val c: whitebox.Context) { resTree } - /** - * Check the input tree of the annotation. + /** Check the input tree of the annotation. * - * @param annottees + * @param annottees */ def checkAnnottees(annottees: Seq[Expr[Any]]): Unit = {} - /** - * Eval the input tree. + /** Eval the input tree. * - * @param tree - * @tparam T - * @return + * @param tree + * @tparam T + * @return */ def evalTree[T: WeakTypeTag](tree: Tree): T = c.eval(c.Expr[T](c.untypecheck(tree.duplicate))) - /** - * Output ast result. + /** Output ast result. * - * @param force - * @param resTree + * @param force + * @param resTree */ def printTree(force: Boolean, resTree: Tree): Unit = c.info( @@ -89,24 +87,24 @@ abstract class AbstractMacroProcessor(val c: whitebox.Context) { force = false ) - /** - * Check the class and its companion object, and return the class definition. + /** Check the class and its companion object, and return the class definition. * - * @param annottees - * @return Return a [[scala.reflect.api.Trees#ClassDef]] + * @param annottees + * @return + * Return a [[scala.reflect.api.Trees#ClassDef]] */ def checkGetClassDef(annottees: Seq[Expr[Any]]): ClassDef = annottees.map(_.tree).toList match { case (classDecl: ClassDef) :: Nil => classDecl case (classDecl: ClassDef) :: (_: ModuleDef) :: Nil => classDecl - case _ => c.abort(c.enclosingPosition, ErrorMessage.UNEXPECTED_PATTERN) + case _ => c.abort(c.enclosingPosition, ErrorMessage.UNEXPECTED_PATTERN) } - /** - * Get object if it exists. + /** Get object if it exists. * - * @param annottees - * @return Return a optional [[scala.reflect.api.Trees#ModuleDef]] + * @param annottees + * @return + * Return a optional [[scala.reflect.api.Trees#ModuleDef]] */ def getModuleDefOption(annottees: Seq[Expr[Any]]): Option[ModuleDef] = annottees.map(_.tree).toList match { @@ -117,12 +115,13 @@ abstract class AbstractMacroProcessor(val c: whitebox.Context) { case _ => None } - /** - * Modify the associated object itself according to whether there is an associated object. + /** Modify the associated object itself according to whether there is an associated object. * - * @param annottees - * @param modifyAction The actual processing function - * @return Return the result of modifyAction function + * @param annottees + * @param modifyAction + * The actual processing function + * @return + * Return the result of modifyAction function */ def collectCustomExpr( annottees: Seq[Expr[Any]] @@ -132,27 +131,29 @@ abstract class AbstractMacroProcessor(val c: whitebox.Context) { modifyAction(classDef, compDecl).asInstanceOf[Expr[Nothing]] } - /** - * Check whether the class is a case class. + /** Check whether the class is a case class. * - * @param annotateeClass classDef - * @return Return true if it is a case class + * @param annotateeClass + * classDef + * @return + * Return true if it is a case class */ def isCaseClass(annotateeClass: ClassDef): Boolean = annotateeClass.mods.hasFlag(Flag.CASE) - /** - * Check whether the mods of the fields has a `private[this]` or `protected[this]`, because it cannot be used out of class. + /** Check whether the mods of the fields has a `private[this]` or `protected[this]`, because it cannot be used out of + * class. * - * @param tree Tree is a field or method? - * @return Return false if mods exists `private[this]` or `protected[this]` + * @param tree + * Tree is a field or method? + * @return + * Return false if mods exists `private[this]` or `protected[this]` */ def isNotLocalClassMember(tree: Tree): Boolean = { - lazy val modifierNotLocal = (mods: Modifiers) => { + lazy val modifierNotLocal = (mods: Modifiers) => !( mods.hasFlag(Flag.PRIVATE | Flag.LOCAL) | mods.hasFlag(Flag.PROTECTED | Flag.LOCAL) ) - } tree match { case v: ValDef => modifierNotLocal(v.mods) case d: DefDef => modifierNotLocal(d.mods) @@ -160,36 +161,37 @@ abstract class AbstractMacroProcessor(val c: whitebox.Context) { } } - /** - * Get the field TermName with type. + /** Get the field TermName with type. * - * @param annotteeClassParams - * @return Return a sequence of [[scala.reflect.api.Trees#Tree]], each one is `tname: tpt` + * @param annotteeClassParams + * @return + * Return a sequence of [[scala.reflect.api.Trees#Tree]], each one is `tname: tpt` */ def getConstructorParamsNameWithType(annotteeClassParams: Seq[Tree]): Seq[Tree] = annotteeClassParams.map(_.asInstanceOf[ValDef]).map(v => q"${v.name}: ${v.tpt}") - /** - * Modify companion object or object. + /** Modify companion object or object. * - * @param compDeclOpt - * @param codeBlocks - * @param className - * @return Return a [[scala.reflect.api.Trees#ModuleDef]] which was appended codeblocks, ModuleDef may already exist or may be newly created + * @param compDeclOpt + * @param codeBlocks + * @param className + * @return + * Return a [[scala.reflect.api.Trees#ModuleDef]] which was appended codeblocks, ModuleDef may already exist or may + * be newly created */ def appendModuleBody(compDeclOpt: Option[ModuleDef], codeBlocks: List[Tree], className: TypeName): Tree = compDeclOpt.fold(q"object ${className.toTermName} { ..$codeBlocks }") { compDecl => - val ModuleDef(mods, name, impl) = compDecl + val ModuleDef(mods, name, impl) = compDecl val Template(parents, self, body) = impl - val newImpl = Template(parents, self, body ++ codeBlocks) + val newImpl = Template(parents, self, body ++ codeBlocks) ModuleDef(mods, name, newImpl) } - /** - * Extract the internal fields of members belonging to the class, but not in primary constructor. + /** Extract the internal fields of members belonging to the class, but not in primary constructor. * - * @param annotteeClassDefinitions - * @return Return a sequence of [[scala.reflect.api.Trees#ValDef]] + * @param annotteeClassDefinitions + * @return + * Return a sequence of [[scala.reflect.api.Trees#ValDef]] */ def getClassMemberValDefs(annotteeClassDefinitions: Seq[Tree]): Seq[ValDef] = annotteeClassDefinitions @@ -199,29 +201,29 @@ abstract class AbstractMacroProcessor(val c: whitebox.Context) { }) .map(_.asInstanceOf[ValDef]) - /** - * Extract the constructor params ValDef and flatten for currying. + /** Extract the constructor params ValDef and flatten for currying. * - * @param annotteeClassParams - * @return Return a sequence of [[scala.reflect.api.Trees#ValDef]] + * @param annotteeClassParams + * @return + * Return a sequence of [[scala.reflect.api.Trees#ValDef]] */ def getClassConstructorValDefsFlatten(annotteeClassParams: List[List[Tree]]): Seq[ValDef] = annotteeClassParams.flatten.map(_.asInstanceOf[ValDef]) - /** - * Extract the constructor params [[scala.reflect.api.Trees#ValDef]] not flatten. + /** Extract the constructor params [[scala.reflect.api.Trees#ValDef]] not flatten. * - * @param annotteeClassParams - * @return Return a double sequence of [[scala.reflect.api.Trees#ValDef]] + * @param annotteeClassParams + * @return + * Return a double sequence of [[scala.reflect.api.Trees#ValDef]] */ def getClassConstructorValDefsNotFlatten(annotteeClassParams: List[List[Tree]]): Seq[Seq[ValDef]] = annotteeClassParams.map(_.map(_.asInstanceOf[ValDef])) - /** - * Extract the methods belonging to the class, contains Secondary Constructor. + /** Extract the methods belonging to the class, contains Secondary Constructor. * - * @param annotteeClassDefinitions - * @return Return a sequence of [[scala.reflect.api.Trees#DefDef]] + * @param annotteeClassDefinitions + * @return + * Return a sequence of [[scala.reflect.api.Trees#DefDef]] */ def getClassMemberDefDefs(annotteeClassDefinitions: Seq[Tree]): Seq[DefDef] = annotteeClassDefinitions @@ -231,22 +233,23 @@ abstract class AbstractMacroProcessor(val c: whitebox.Context) { }) .map(_.asInstanceOf[DefDef]) - /** - * We generate constructor with currying, and we have to deal with the first layer of currying alone. + /** We generate constructor with currying, and we have to deal with the first layer of currying alone. * - * @param typeName - * @param fieldss - * @param isCase - * @return A constructor with currying, it not contains tpt, provide for calling method. - * @example Return a tree, such as `new TestClass12(i)(j)(k)(t)` + * @param typeName + * @param fieldss + * @param isCase + * @return + * A constructor with currying, it not contains tpt, provide for calling method. + * @example + * Return a tree, such as `new TestClass12(i)(j)(k)(t)` */ def getConstructorWithCurrying(typeName: TypeName, fieldss: List[List[Tree]], isCase: Boolean): Tree = { val fieldssValDefNotFlatten = getClassConstructorValDefsNotFlatten(fieldss) - val allFieldsTermName = fieldssValDefNotFlatten.map(_.map(_.name.toTermName)) + val allFieldsTermName = fieldssValDefNotFlatten.map(_.map(_.name.toTermName)) // not currying val constructor = if (fieldss.isEmpty || fieldss.size == 1) { q"${if (isCase) q"${typeName.toTermName}(..${allFieldsTermName.flatten})" - else q"new $typeName(..${allFieldsTermName.flatten})"}" + else q"new $typeName(..${allFieldsTermName.flatten})"}" } else { // currying val first = allFieldsTermName.head @@ -256,42 +259,43 @@ abstract class AbstractMacroProcessor(val c: whitebox.Context) { constructor } - /** - * Only for primitive types, we can get type and map to scala type. + /** Only for primitive types, we can get type and map to scala type. * - * @param javaType java type name - * @return Scala type name + * @param javaType + * java type name + * @return + * Scala type name */ def toScalaType(javaType: String): String = { val types = Map( - "java.lang.Integer" -> "Int", - "java.lang.Long" -> "Long", - "java.lang.Double" -> "Double", - "java.lang.Float" -> "Float", - "java.lang.Short" -> "Short", - "java.lang.Byte" -> "Byte", - "java.lang.Boolean" -> "Boolean", + "java.lang.Integer" -> "Int", + "java.lang.Long" -> "Long", + "java.lang.Double" -> "Double", + "java.lang.Float" -> "Float", + "java.lang.Short" -> "Short", + "java.lang.Byte" -> "Byte", + "java.lang.Boolean" -> "Boolean", "java.lang.Character" -> "Char", - "java.lang.String" -> "String" + "java.lang.String" -> "String" ) types.getOrElse(javaType, javaType) } - /** - * Gets a list of generic parameters. - * This is because the generic parameters of a class cannot be used directly in the return type, and need to be converted. + /** Gets a list of generic parameters. This is because the generic parameters of a class cannot be used directly in + * the return type, and need to be converted. * - * @param tpParams - * @return Return a sequence of [[scala.reflect.api.Names#TypeName]] + * @param tpParams + * @return + * Return a sequence of [[scala.reflect.api.Names#TypeName]] */ def extractClassTypeParamsTypeName(tpParams: List[Tree]): List[TypeName] = tpParams.map(_.asInstanceOf[TypeDef].name) - /** - * Is there a parent class? Does not contains sdk class, such as AnyRef and Object. + /** Is there a parent class? Does not contains sdk class, such as AnyRef and Object. * - * @param superClasses - * @return Return true if there is a non-SDK super class + * @param superClasses + * @return + * Return true if there is a non-SDK super class */ def existsSuperClassExcludeSdkClass(superClasses: Seq[Tree]): Boolean = superClasses.nonEmpty && !superClasses.forall(sc => SDKClasses.contains(sc.toString())) @@ -310,22 +314,25 @@ abstract class AbstractMacroProcessor(val c: whitebox.Context) { def paramType: Type = c.typecheck(tq"$tpt", c.TYPEmode).tpe } - /** - * Retrieves the accessor fields on a class and returns a Seq of [[org.bitlap.tools.macros.AbstractMacroProcessor#ValDefAccessor]]. + /** Retrieves the accessor fields on a class and returns a Seq of + * [[org.bitlap.tools.macros.AbstractMacroProcessor#ValDefAccessor]]. * - * @param params The list of params retrieved from the class - * @return Return a sequence of [[org.bitlap.tools.macros.AbstractMacroProcessor#ValDefAccessor]] + * @param params + * The list of params retrieved from the class + * @return + * Return a sequence of [[org.bitlap.tools.macros.AbstractMacroProcessor#ValDefAccessor]] */ def valDefAccessors(params: Seq[Tree]): Seq[ValDefAccessor] = params.map { case ValDef(mods, name: TermName, tpt: Tree, rhs) => ValDefAccessor(mods, name, tpt, rhs) } - /** - * Extract the necessary structure information of the class for macro programming. + /** Extract the necessary structure information of the class for macro programming. * - * @param classDecl - * @return Return the expansion of the class definition as [[org.bitlap.tools.macros.AbstractMacroProcessor#ClassDefinition]] + * @param classDecl + * @return + * Return the expansion of the class definition as + * [[org.bitlap.tools.macros.AbstractMacroProcessor#ClassDefinition]] */ def mapToClassDeclInfo(classDecl: ClassDef): ClassDefinition = { val q"$mods class $tpname[..$tparams] $ctorMods(...$paramss) extends { ..$earlydefns } with ..$parents { $self => ..$stats }" = @@ -343,11 +350,12 @@ abstract class AbstractMacroProcessor(val c: whitebox.Context) { ) } - /** - * Extract the necessary structure information of the moduleDef for macro programming. + /** Extract the necessary structure information of the moduleDef for macro programming. * - * @param moduleDef - * @return Return the expansion of the class definition as [[org.bitlap.tools.macros.AbstractMacroProcessor#ClassDefinition]] + * @param moduleDef + * @return + * Return the expansion of the class definition as + * [[org.bitlap.tools.macros.AbstractMacroProcessor#ClassDefinition]] */ def mapToModuleDeclInfo(moduleDef: ModuleDef): ClassDefinition = { val q"$mods object $tpname extends { ..$earlydefns } with ..$parents { $self => ..$stats }" = moduleDef @@ -362,18 +370,19 @@ abstract class AbstractMacroProcessor(val c: whitebox.Context) { ) } - /** - * Generate the specified syntax tree and assign it to the tree definition itself. - * Used only when you modify the definition of the class itself. Such as add method/add field. + /** Generate the specified syntax tree and assign it to the tree definition itself. Used only when you modify the + * definition of the class itself. Such as add method/add field. * - * @param classDecl - * @param classInfoAction Content body added in class definition - * @return Return a new [[scala.reflect.api.Trees#ClassDef]] + * @param classDecl + * @param classInfoAction + * Content body added in class definition + * @return + * Return a new [[scala.reflect.api.Trees#ClassDef]] */ def appendClassBody(classDecl: ClassDef, classInfoAction: ClassDefinition => List[Tree]): c.universe.ClassDef = { - val classInfo = mapToClassDeclInfo(classDecl) + val classInfo = mapToClassDeclInfo(classDecl) val ClassDef(mods, name, tparams, impl) = classDecl - val Template(parents, self, body) = impl + val Template(parents, self, body) = impl ClassDef(mods, name, tparams, Template(parents, self, body ++ classInfoAction(classInfo))) } @@ -404,12 +413,13 @@ abstract class AbstractMacroProcessor(val c: whitebox.Context) { q"$mods object $tpname extends { ..$earlydefns } with ..${parents.toList ++ classInfoAction(classInfo)} { $self => ..$stats }" } - /** - * Modify the method body of the method tree. + /** Modify the method body of the method tree. * - * @param defDef - * @param defBodyAction Method body of final result - * @return Return a new [[scala.reflect.api.Trees#DefDef]] which changed by defBodyAction function + * @param defDef + * @param defBodyAction + * Method body of final result + * @return + * Return a new [[scala.reflect.api.Trees#DefDef]] which changed by defBodyAction function */ def mapToMethodDef(defDef: DefDef, defBodyAction: => Tree): c.universe.DefDef = { val DefDef(mods, name, tparams, vparamss, tpt, rhs) = defDef @@ -427,11 +437,11 @@ abstract class AbstractMacroProcessor(val c: whitebox.Context) { earlydefns: List[Tree] = Nil ) - /** - * Find the specified val Name in the enclosingClass definition. + /** Find the specified val Name in the enclosingClass definition. * - * @param t - * @return Return a optional [[scala.reflect.api.Names#TermName]] + * @param t + * @return + * Return a optional [[scala.reflect.api.Names#TermName]] */ def findValDefInEnclosingClass(t: Name): Option[TermName] = { @tailrec @@ -440,7 +450,7 @@ abstract class AbstractMacroProcessor(val c: whitebox.Context) { case tree :: tail => tree match { case ValDef(_, name, tpt, _) => - if (c.typecheck(tq"$tpt", c.TYPEmode).tpe.toString == t.decodedName.toString) //TODO better + if (c.typecheck(tq"$tpt", c.TYPEmode).tpe.toString == t.decodedName.toString) // TODO better Some(name.toTermName) else None case _ => doFind(tail) diff --git a/smt-tools/src/main/scala/org/bitlap/tools/macros/applyMacro.scala b/smt-tools/src/main/scala/org/bitlap/tools/macros/applyMacro.scala index 510443894dc0d4dc4d9dba0a80d8b5599172e72e..8ee940a26d7a95ccf00a3acc898fff3ef90f9d64 100644 --- a/smt-tools/src/main/scala/org/bitlap/tools/macros/applyMacro.scala +++ b/smt-tools/src/main/scala/org/bitlap/tools/macros/applyMacro.scala @@ -23,10 +23,10 @@ package org.bitlap.tools.macros import scala.reflect.macros.whitebox -/** - * @author 梦境迷离 - * @since 2021/7/7 - * @version 1.0 +/** @author + * 梦境迷离 + * @since 2021/7/7 + * @version 1.0 */ object applyMacro { @@ -34,13 +34,15 @@ object applyMacro { import c.universe._ - /** - * We generate apply method with currying, and we have to deal with the first layer of currying alone. + /** We generate apply method with currying, and we have to deal with the first layer of currying alone. * - * @param typeName - * @param fieldss - * @return A apply method with currying. - * @example Return a tree, such as `def apply(int: Int)(j: Int)(k: Option[String])(t: Option[Long]): B3 = new B3(int)(j)(k)(t)` + * @param typeName + * @param fieldss + * @return + * A apply method with currying. + * @example + * Return a tree, such as `def apply(int: Int)(j: Int)(k: Option[String])(t: Option[Long]): B3 = new + * B3(int)(j)(k)(t)` */ private def getApplyMethodWithCurrying( typeName: TypeName, @@ -48,7 +50,7 @@ object applyMacro { classTypeParams: List[Tree] ): Tree = { val allFieldsTermName = fieldss.map(f => getConstructorParamsNameWithType(f)) - val returnTypeParams = extractClassTypeParamsTypeName(classTypeParams) + val returnTypeParams = extractClassTypeParamsTypeName(classTypeParams) // not currying val applyMethod = if (fieldss.isEmpty || fieldss.size == 1) { q"def apply[..$classTypeParams](..${allFieldsTermName.flatten}): $typeName[..$returnTypeParams] = ${getConstructorWithCurrying(typeName, fieldss, isCase = false)}" diff --git a/smt-tools/src/main/scala/org/bitlap/tools/macros/builderMacro.scala b/smt-tools/src/main/scala/org/bitlap/tools/macros/builderMacro.scala index ce8b6451376b897a8891ba4d4687316f1d79b385..607cc78dfb70245917b48692415b890589af9432 100644 --- a/smt-tools/src/main/scala/org/bitlap/tools/macros/builderMacro.scala +++ b/smt-tools/src/main/scala/org/bitlap/tools/macros/builderMacro.scala @@ -23,10 +23,10 @@ package org.bitlap.tools.macros import scala.reflect.macros.whitebox -/** - * @author 梦境迷离 - * @since 2021/7/7 - * @version 1.0 +/** @author + * 梦境迷离 + * @since 2021/7/7 + * @version 1.0 */ object builderMacro { @@ -45,14 +45,12 @@ object builderMacro { private def getFieldSetMethod(typeName: TypeName, field: Tree, classTypeParams: List[Tree]): Tree = { val builderClassName = getBuilderClassName(typeName) val returnTypeParams = extractClassTypeParamsTypeName(classTypeParams) - lazy val valDefMapTo = (v: ValDef) => { - q""" + lazy val valDefMapTo = (v: ValDef) => q""" def ${v.name}(${v.name}: ${v.tpt}): $builderClassName[..$returnTypeParams] = { this.${v.name} = ${v.name} this } """ - } valDefMapTo(field.asInstanceOf[ValDef]) } @@ -62,11 +60,11 @@ object builderMacro { classTypeParams: List[Tree], isCase: Boolean ): List[Tree] = { - val fields = fieldss.flatten - val builderClassName = getBuilderClassName(typeName) - val builderFieldMethods = fields.map(f => getFieldSetMethod(typeName, f, classTypeParams)) + val fields = fieldss.flatten + val builderClassName = getBuilderClassName(typeName) + val builderFieldMethods = fields.map(f => getFieldSetMethod(typeName, f, classTypeParams)) val builderFieldDefinitions = fields.map(f => getFieldDefinition(f)) - val returnTypeParams = extractClassTypeParamsTypeName(classTypeParams) + val returnTypeParams = extractClassTypeParamsTypeName(classTypeParams) val builderMethod = q"def builder[..$classTypeParams](): $builderClassName[..$returnTypeParams] = new $builderClassName()" val buulderClass = diff --git a/smt-tools/src/main/scala/org/bitlap/tools/macros/constructorMacro.scala b/smt-tools/src/main/scala/org/bitlap/tools/macros/constructorMacro.scala index ed281b91f162b7402647be382629460dfe603d25..380875d755a00081338fa60a7cc09dfae816eb56 100644 --- a/smt-tools/src/main/scala/org/bitlap/tools/macros/constructorMacro.scala +++ b/smt-tools/src/main/scala/org/bitlap/tools/macros/constructorMacro.scala @@ -23,10 +23,10 @@ package org.bitlap.tools.macros import scala.reflect.macros.whitebox -/** - * @author 梦境迷离 - * @since 2021/7/7 - * @version 1.0 +/** @author + * 梦境迷离 + * @since 2021/7/7 + * @version 1.0 */ object constructorMacro { @@ -34,23 +34,21 @@ object constructorMacro { import c.universe._ - private val extractArgs: Seq[String] = { + private val extractArgs: Seq[String] = c.prefix.tree match { case q"new constructor(excludeFields=$excludeFields)" => evalTree(excludeFields.asInstanceOf[Tree]) case q"new constructor($excludeFields)" => evalTree(excludeFields.asInstanceOf[Tree]) case q"new constructor()" => Seq.empty[String] - case _ => c.abort(c.enclosingPosition, ErrorMessage.UNEXPECTED_PATTERN) + case _ => c.abort(c.enclosingPosition, ErrorMessage.UNEXPECTED_PATTERN) } - } private def getMutableValDefAndExcludeFields(annotteeClassDefinitions: Seq[Tree]): Seq[c.universe.ValDef] = getClassMemberValDefs(annotteeClassDefinitions).filter(v => v.mods.hasFlag(Flag.MUTABLE) && - !extractArgs.contains(v.name.decodedName.toString) + !extractArgs.contains(v.name.decodedName.toString) ) - /** - * Extract the internal fields of members belonging to the class, but not in primary constructor and only `var`. + /** Extract the internal fields of members belonging to the class, but not in primary constructor and only `var`. */ private def getMemberVarDefTermNameWithType(annotteeClassDefinitions: Seq[Tree]): Seq[Tree] = getMutableValDefAndExcludeFields(annotteeClassDefinitions).map { v => @@ -62,8 +60,7 @@ object constructorMacro { } } - /** - * We generate this method with currying, and we have to deal with the first layer of currying alone. + /** We generate this method with currying, and we have to deal with the first layer of currying alone. */ private def getThisMethodWithCurrying( annotteeClassParams: List[List[Tree]], diff --git a/smt-tools/src/main/scala/org/bitlap/tools/macros/elapsedMacro.scala b/smt-tools/src/main/scala/org/bitlap/tools/macros/elapsedMacro.scala index 3d2d285728d386f8d9050de2a8043cff5b33eef3..add4b7501bacf75be76ae8cc7821691cd814d316 100644 --- a/smt-tools/src/main/scala/org/bitlap/tools/macros/elapsedMacro.scala +++ b/smt-tools/src/main/scala/org/bitlap/tools/macros/elapsedMacro.scala @@ -28,13 +28,14 @@ import scala.concurrent.duration._ import scala.reflect.macros.whitebox /** - * 1. This annotation only support use on non-abstract method. - * 2. For methods that are not future, `try finally` is used to implement the timing of the method. - * 3. For methods that are Futures, `Future map` is used to implement the timing of the method. + * 1. This annotation only support use on non-abstract method. 2. For methods that are not future, `try finally` is + * used to implement the timing of the method. 3. For methods that are Futures, `Future map` is used to implement + * the timing of the method. * - * @author 梦境迷离 - * @since 2021/8/7 - * @version 1.0 + * @author + * 梦境迷离 + * @since 2021/8/7 + * @version 1.0 */ object elapsedMacro { @@ -42,7 +43,7 @@ object elapsedMacro { import c.universe._ - private lazy val start: c.universe.TermName = TermName("$elapsedBegin") + private lazy val start: c.universe.TermName = TermName("$elapsedBegin") private lazy val valDef: c.universe.TermName = TermName("$elapsed") private def getLogLevel(logLevel: Tree): LogLevel = @@ -99,10 +100,13 @@ object elapsedMacro { private def getNewMethodWithFuture(defDef: DefDef): DefDef = mapToNewMethod( defDef, - defDef => q""" + defDef => + q""" $getStartExpr val resFuture = ${defDef.rhs} - resFuture.map { res => ..${getPrintlnLog(defDef.name)} ; res }(_root_.scala.concurrent.ExecutionContext.Implicits.global) + resFuture.map { res => ..${getPrintlnLog( + defDef.name + )} ; res }(_root_.scala.concurrent.ExecutionContext.Implicits.global) """ ) diff --git a/smt-tools/src/main/scala/org/bitlap/tools/macros/equalsAndHashCodeMacro.scala b/smt-tools/src/main/scala/org/bitlap/tools/macros/equalsAndHashCodeMacro.scala index 8807b37024ff367ce251f18cd92f72442521bfb6..13d4b70f12073a786ee7aa7f20faab621f1c9966 100644 --- a/smt-tools/src/main/scala/org/bitlap/tools/macros/equalsAndHashCodeMacro.scala +++ b/smt-tools/src/main/scala/org/bitlap/tools/macros/equalsAndHashCodeMacro.scala @@ -23,10 +23,10 @@ package org.bitlap.tools.macros import scala.reflect.macros.whitebox -/** - * @author 梦境迷离 - * @since 2021/7/18 - * @version 1.0 +/** @author + * 梦境迷离 + * @since 2021/7/18 + * @version 1.0 */ object equalsAndHashCodeMacro { @@ -38,7 +38,7 @@ object equalsAndHashCodeMacro { case q"new equalsAndHashCode(excludeFields=$excludeFields)" => evalTree(excludeFields.asInstanceOf[Tree]) case q"new equalsAndHashCode($excludeFields)" => evalTree(excludeFields.asInstanceOf[Tree]) case q"new equalsAndHashCode()" => Nil - case _ => c.abort(c.enclosingPosition, ErrorMessage.UNEXPECTED_PATTERN) + case _ => c.abort(c.enclosingPosition, ErrorMessage.UNEXPECTED_PATTERN) } override def checkAnnottees(annottees: Seq[c.universe.Expr[Any]]): Unit = { @@ -49,8 +49,7 @@ object equalsAndHashCodeMacro { } } - /** - * Extract the internal fields of members belonging to the class. + /** Extract the internal fields of members belonging to the class. */ private def getInternalFieldsTermNameExcludeLocal(annotteeClassDefinitions: Seq[Tree]): Seq[TermName] = { if (annotteeClassDefinitions.exists(f => isNotLocalClassMember(f))) { @@ -59,7 +58,7 @@ object equalsAndHashCodeMacro { getClassMemberValDefs(annotteeClassDefinitions) .filter(p => isNotLocalClassMember(p) && - !extractArgs.contains(p.name.decodedName.toString) + !extractArgs.contains(p.name.decodedName.toString) ) .map(_.name.toTermName) } @@ -88,9 +87,9 @@ object equalsAndHashCodeMacro { override def equals(that: Any): Boolean = that match { case t: $className => t.canEqual(this) && Seq(..$equalsExprs).forall(f => f) && ${if ( - existsSuperClassExcludeSdkClass(superClasses) - ) q"super.equals(that)" - else q"true"} + existsSuperClassExcludeSdkClass(superClasses) + ) q"super.equals(that)" + else q"true"} case _ => false } """ @@ -105,20 +104,19 @@ object equalsAndHashCodeMacro { override def hashCode(): Int = { val state = Seq(..$termNames) state.map(_.hashCode()).foldLeft(0)((a, b) => 31 * a + b) + ${if ( - existsSuperClassExcludeSdkClass(superClasses) - ) superTree - else q"0"} + existsSuperClassExcludeSdkClass(superClasses) + ) superTree + else q"0"} } """ } override def createCustomExpr(classDecl: ClassDef, compDeclOpt: Option[ModuleDef]): Any = { - lazy val map = (classDefinition: ClassDefinition) => { + lazy val map = (classDefinition: ClassDefinition) => getClassConstructorValDefsFlatten(classDefinition.classParamss) .filter(cf => isNotLocalClassMember(cf)) .map(_.name.toTermName) ++ getInternalFieldsTermNameExcludeLocal(classDefinition.body) - } val classDefinition = mapToClassDeclInfo(classDecl) val res = appendClassBody( classDecl, diff --git a/smt-tools/src/main/scala/org/bitlap/tools/macros/jacksonEnumMacro.scala b/smt-tools/src/main/scala/org/bitlap/tools/macros/jacksonEnumMacro.scala index 1563eb73f936d8f2193e3057ae249dd3ce51a1bd..155649fdb17801f5ac889d7156485768bbb29009 100644 --- a/smt-tools/src/main/scala/org/bitlap/tools/macros/jacksonEnumMacro.scala +++ b/smt-tools/src/main/scala/org/bitlap/tools/macros/jacksonEnumMacro.scala @@ -29,14 +29,13 @@ object jacksonEnumMacro { import c.universe._ - private val extractArgs: Seq[String] = { + private val extractArgs: Seq[String] = c.prefix.tree match { case q"new jacksonEnum(nonTypeRefers=$nonTypeRefers)" => evalTree(nonTypeRefers.asInstanceOf[Tree]) case q"new jacksonEnum($nonTypeRefers)" => evalTree(nonTypeRefers.asInstanceOf[Tree]) case q"new jacksonEnum()" => Nil - case _ => c.abort(c.enclosingPosition, ErrorMessage.UNEXPECTED_PATTERN) + case _ => c.abort(c.enclosingPosition, ErrorMessage.UNEXPECTED_PATTERN) } - } private def getJacksonTypeReferClasses(valDefs: List[ValDef]): Seq[Tree] = { val safeValDefs = valDefAccessors(valDefs) @@ -48,8 +47,8 @@ object jacksonEnumMacro { .distinct .map(c => q"""class ${TypeName( - c.decodedName.toString + "TypeRefer" - )} extends _root_.com.fasterxml.jackson.core.`type`.TypeReference[$c.type]""" + c.decodedName.toString + "TypeRefer" + )} extends _root_.com.fasterxml.jackson.core.`type`.TypeReference[$c.type]""" ) } @@ -85,12 +84,12 @@ object jacksonEnumMacro { override def createCustomExpr(classDecl: c.universe.ClassDef, compDeclOpt: Option[c.universe.ModuleDef]): Any = { // return all typeReferClasses and new classDef - val classDefinition = mapToClassDeclInfo(classDecl) - val valDefs = classDefinition.classParamss.flatten.map(_.asInstanceOf[ValDef]) + val classDefinition = mapToClassDeclInfo(classDecl) + val valDefs = classDefinition.classParamss.flatten.map(_.asInstanceOf[ValDef]) val typeReferClasses = getJacksonTypeReferClasses(valDefs).distinct val q"$mods class $tpname[..$tparams] $ctorMods(...$paramss) extends ..$bases { ..$body }" = classDecl val newFieldss = paramss.asInstanceOf[List[List[Tree]]].map(_.map(replaceAnnotation)) - val newClass = q"$mods class $tpname[..$tparams] $ctorMods(...$newFieldss) extends ..$bases { ..$body }" + val newClass = q"$mods class $tpname[..$tparams] $ctorMods(...$newFieldss) extends ..$bases { ..$body }" val res = q""" ..$typeReferClasses diff --git a/smt-tools/src/main/scala/org/bitlap/tools/macros/javaCompatibleMacro.scala b/smt-tools/src/main/scala/org/bitlap/tools/macros/javaCompatibleMacro.scala index 5b7b7b89d137d3672beb991259dd3584a79e7892..6334d8859c7f1eb18db14493df85a3789b9b6af4 100644 --- a/smt-tools/src/main/scala/org/bitlap/tools/macros/javaCompatibleMacro.scala +++ b/smt-tools/src/main/scala/org/bitlap/tools/macros/javaCompatibleMacro.scala @@ -23,10 +23,10 @@ package org.bitlap.tools.macros import scala.reflect.macros.whitebox -/** - * @author 梦境迷离 - * @since 2021/11/23 - * @version 1.0 +/** @author + * 梦境迷离 + * @since 2021/11/23 + * @version 1.0 */ object javaCompatibleMacro { @@ -34,8 +34,7 @@ object javaCompatibleMacro { import c.universe._ - /** - * We generate this method with currying, and we have to deal with the first layer of currying alone. + /** We generate this method with currying, and we have to deal with the first layer of currying alone. */ private def getNoArgsContrWithCurrying( annotteeClassParams: List[List[Tree]], diff --git a/smt-tools/src/main/scala/org/bitlap/tools/macros/jsonMacro.scala b/smt-tools/src/main/scala/org/bitlap/tools/macros/jsonMacro.scala index d429f78337fa61f1a405c9959366d3269e1ddfa1..c1755a4fd6a14684525356bd622c9e513358069e 100644 --- a/smt-tools/src/main/scala/org/bitlap/tools/macros/jsonMacro.scala +++ b/smt-tools/src/main/scala/org/bitlap/tools/macros/jsonMacro.scala @@ -23,10 +23,10 @@ package org.bitlap.tools.macros import scala.reflect.macros.whitebox -/** - * @author 梦境迷离 - * @since 2021/7/7 - * @version 1.0 +/** @author + * 梦境迷离 + * @since 2021/7/7 + * @version 1.0 */ object jsonMacro { @@ -51,8 +51,8 @@ object jsonMacro { override def createCustomExpr(classDecl: c.universe.ClassDef, compDeclOpt: Option[c.universe.ModuleDef]): Any = { val classDefinition = mapToClassDeclInfo(classDecl) - val format = jsonFormatter(classDefinition.className, classDefinition.classParamss.flatten) - val compDecl = appendModuleBody(compDeclOpt, List(format), classDefinition.className) + val format = jsonFormatter(classDefinition.className, classDefinition.classParamss.flatten) + val compDecl = appendModuleBody(compDeclOpt, List(format), classDefinition.className) // Return both the class and companion object declarations c.Expr(q""" $classDecl diff --git a/smt-tools/src/main/scala/org/bitlap/tools/macros/logMacro.scala b/smt-tools/src/main/scala/org/bitlap/tools/macros/logMacro.scala index 0e2fa653ea6295a7613e4315c7e8f156631f8bde..842b526304d9f34e6c8e7e65386cea636daa2ca7 100644 --- a/smt-tools/src/main/scala/org/bitlap/tools/macros/logMacro.scala +++ b/smt-tools/src/main/scala/org/bitlap/tools/macros/logMacro.scala @@ -27,10 +27,10 @@ import org.bitlap.tools.{ logs, PACKAGE } import scala.reflect.macros.whitebox -/** - * @author 梦境迷离 - * @since 2021/7/7 - * @version 1.0 +/** @author + * 梦境迷离 + * @since 2021/7/7 + * @version 1.0 */ object logMacro { diff --git a/smt-tools/src/main/scala/org/bitlap/tools/macros/macros.scala b/smt-tools/src/main/scala/org/bitlap/tools/macros/macros.scala index a03a9b30834b358e80282c385bcff440cdda178a..f7e66725cde3ac33be465df3b90b602e7f993b4c 100644 --- a/smt-tools/src/main/scala/org/bitlap/tools/macros/macros.scala +++ b/smt-tools/src/main/scala/org/bitlap/tools/macros/macros.scala @@ -21,18 +21,18 @@ package org.bitlap.tools -/** - * @author 梦境迷离 - * @since 2021/7/7 - * @version 1.0 +/** @author + * 梦境迷离 + * @since 2021/7/7 + * @version 1.0 */ package object macros { private[macros] object ErrorMessage { // common error msg - final lazy val ONLY_CLASS: String = "Annotation is only supported on class." - final lazy val ONLY_CASE_CLASS: String = "Annotation is only supported on case class." - final lazy val ONLY_OBJECT_CLASS: String = "Annotation is only supported on class or object." + final lazy val ONLY_CLASS: String = "Annotation is only supported on class." + final lazy val ONLY_CASE_CLASS: String = "Annotation is only supported on case class." + final lazy val ONLY_OBJECT_CLASS: String = "Annotation is only supported on class or object." final lazy val UNEXPECTED_PATTERN: String = "Unexpected annotation pattern!" } diff --git a/smt-tools/src/main/scala/org/bitlap/tools/macros/toStringMacro.scala b/smt-tools/src/main/scala/org/bitlap/tools/macros/toStringMacro.scala index 3e2a8e9f814f87e3c03877d6af16a487f38d5491..fde16591afd86765003b0139d3370aa54cba28d9 100644 --- a/smt-tools/src/main/scala/org/bitlap/tools/macros/toStringMacro.scala +++ b/smt-tools/src/main/scala/org/bitlap/tools/macros/toStringMacro.scala @@ -23,10 +23,10 @@ package org.bitlap.tools.macros import scala.reflect.macros.whitebox -/** - * @author 梦境迷离 - * @since 2021/7/7 - * @version 1.0 +/** @author + * 梦境迷离 + * @since 2021/7/7 + * @version 1.0 */ object toStringMacro { @@ -109,14 +109,14 @@ object toStringMacro { }) val ctorParams = classDefinition.classParamss.flatten - val member = if (argument.includeInternalFields) ctorParams ++ annotteeClassFieldDefinitions else ctorParams + val member = if (argument.includeInternalFields) ctorParams ++ annotteeClassFieldDefinitions else ctorParams val lastParam = member.lastOption.map { case v: ValDef => v.name.toTermName.decodedName.toString case c => c.toString } val paramsWithName = member.foldLeft(q"${""}")((res, acc) => q"$res + ${printField(argument, lastParam, acc)}") - //scala/bug https://github.com/scala/bug/issues/3967 not be 'Foo(i=1,j=2)' in standard library + // scala/bug https://github.com/scala/bug/issues/3967 not be 'Foo(i=1,j=2)' in standard library val toString = q"""override def toString: String = ${classDefinition.className.toTermName.decodedName.toString} + ${"("} + $paramsWithName + ${")"}""" @@ -129,7 +129,7 @@ object toStringMacro { superClassDef.fold(toString) { _ => val superClass = q"${"super="}" q"override def toString: String = StringContext(${classDefinition.className.toTermName.decodedName.toString} + ${"("} + $superClass, ${if (member.nonEmpty) ", " - else ""}+$paramsWithName + ${")"}).s(super.toString)" + else ""}+$paramsWithName + ${")"}).s(super.toString)" } } else { toString diff --git a/smt-tools/src/main/scala/org/bitlap/tools/methods/ProcessorCreator.scala b/smt-tools/src/main/scala/org/bitlap/tools/methods/ProcessorCreator.scala index 5a55ad8c46e1a2351c4f794c95c648968378c1b6..ecc64907f72c9e0aa15e4044c867ca6bb05b1e58 100644 --- a/smt-tools/src/main/scala/org/bitlap/tools/methods/ProcessorCreator.scala +++ b/smt-tools/src/main/scala/org/bitlap/tools/methods/ProcessorCreator.scala @@ -25,29 +25,41 @@ import org.bitlap.tools.methods.impl.ProcessorCreatorMacro import java.util.concurrent.Executor -/** - * The macro util to generate processor for alipay sofa jraft rpc. +/** The macro util to generate processor for alipay sofa jraft rpc. * - * @author 梦境迷离 - * @version 1.0,2021/12/6 + * @author + * 梦境迷离 + * @version 1.0,2021/12/6 */ @deprecated object ProcessorCreator { - /** - * @param service Instance of the `Service` - * @param defaultResp Default instance of the Response Message - * @param executor Instance of the Executor - * @param processRequest Function to handle request - * @param processException Function to handle exception - * @tparam RRC `RpcRequestClosure` - * @tparam RRP `RpcRequestProcessor` - * @tparam RC `RpcContext` - * @tparam Req Request Message of the protobuf - * @tparam Resp Response Message of the protobuf - * @tparam Service Should be custom class/interface/trait which handle the business logic of Processors - * @tparam E Should be subclass of the Executor - * @return [[ RRP ]] Instance of the `RpcRequestProcessor` subclass + /** @param service + * Instance of the `Service` + * @param defaultResp + * Default instance of the Response Message + * @param executor + * Instance of the Executor + * @param processRequest + * Function to handle request + * @param processException + * Function to handle exception + * @tparam RRC + * `RpcRequestClosure` + * @tparam RRP + * `RpcRequestProcessor` + * @tparam RC + * `RpcContext` + * @tparam Req + * Request Message of the protobuf + * @tparam Resp + * Response Message of the protobuf + * @tparam Service + * Should be custom class/interface/trait which handle the business logic of Processors + * @tparam E + * Should be subclass of the Executor + * @return + * [[RRP]] Instance of the `RpcRequestProcessor` subclass */ def apply[RRC, RRP[_ <: Req], RC, Req, Resp, Service, E <: Executor]( defaultResp: Resp, @@ -62,8 +74,8 @@ object ProcessorCreator { )(implicit service: Service): RRP[Req] = macro ProcessorCreatorMacro.WithoutExecutorAndDefaultResp[RRC, RRP[_ <: Req], RC, Req, Resp, Service] - /** - * Having two identical type parameters will cause the compiler to recognize error and change the order of generics to avoid. + /** Having two identical type parameters will cause the compiler to recognize error and change the order of generics + * to avoid. */ def apply[Service, RRC, RRP[_ <: Req], RC, Req, Resp](processRequest: (Service, RRC, Req) => Resp)( processException: (Service, RC, Exception) => Resp diff --git a/smt-tools/src/main/scala/org/bitlap/tools/methods/impl/MacroCache.scala b/smt-tools/src/main/scala/org/bitlap/tools/methods/impl/MacroCache.scala index 6c600e73c8f7027b33d51efdcbcc006ce4f45ed5..bd46fc619f7857026044bb363313216b569d33c5 100644 --- a/smt-tools/src/main/scala/org/bitlap/tools/methods/impl/MacroCache.scala +++ b/smt-tools/src/main/scala/org/bitlap/tools/methods/impl/MacroCache.scala @@ -21,10 +21,10 @@ package org.bitlap.tools.methods.impl -/** - * @author 梦境迷离 - * @since 2022/3/17 - * @version 1.0 +/** @author + * 梦境迷离 + * @since 2022/3/17 + * @version 1.0 */ object MacroCache { diff --git a/smt-tools/src/main/scala/org/bitlap/tools/methods/impl/ProcessorCreatorMacro.scala b/smt-tools/src/main/scala/org/bitlap/tools/methods/impl/ProcessorCreatorMacro.scala index 58cafea1d161b833eb21d4533d59832928c3fa3c..11aef617bf6932d75823557928d318bd10a13c0b 100644 --- a/smt-tools/src/main/scala/org/bitlap/tools/methods/impl/ProcessorCreatorMacro.scala +++ b/smt-tools/src/main/scala/org/bitlap/tools/methods/impl/ProcessorCreatorMacro.scala @@ -25,9 +25,9 @@ import java.time.ZonedDateTime import java.time.format.DateTimeFormatter import scala.reflect.macros.blackbox -/** - * @author 梦境迷离 - * @version 1.0,2021/12/6 +/** @author + * 梦境迷离 + * @version 1.0,2021/12/6 */ object ProcessorCreatorMacro { @@ -48,12 +48,12 @@ object ProcessorCreatorMacro { )(service: c.Expr[Service], executor: c.Expr[E]): c.Expr[RRP] = { // parameters in order, parameter names differ will compile error import c.universe._ checkTree[RRC, RRP, RC, Service](c)(needCheckService = false) - val serviceType = weakTypeOf[Service] - val className = TypeName(classNamePrefix + MacroCache.getIdentityId) - val reqProtoType = weakTypeOf[Req] + val serviceType = weakTypeOf[Service] + val className = TypeName(classNamePrefix + MacroCache.getIdentityId) + val reqProtoType = weakTypeOf[Req] val rpcRequestClosureType = weakTypeOf[RRC] - val rpcContextType = weakTypeOf[RC] - val respProtoType = weakTypeOf[Resp] + val rpcContextType = weakTypeOf[RC] + val respProtoType = weakTypeOf[Resp] val processor = q""" class $className(private val service: $serviceType, executor: java.util.concurrent.Executor = null) @@ -98,13 +98,13 @@ object ProcessorCreatorMacro { )(service: c.Expr[Service]): c.Expr[RRP] = { import c.universe._ checkTree[RRC, RRP, RC, Service](c)(needCheckService = false) - val serviceType = weakTypeOf[Service] - val className = TypeName(classNamePrefix + MacroCache.getIdentityId) - val reqProtoType = weakTypeOf[Req] - val rpcRequestClosureType = weakTypeOf[RRC] - val rpcContextType = weakTypeOf[RC] - val respProtoType = weakTypeOf[Resp] - val respProtoCompanionType = weakTypeOf[Resp].companion //getDefaultInstance is static method, it's in companion + val serviceType = weakTypeOf[Service] + val className = TypeName(classNamePrefix + MacroCache.getIdentityId) + val reqProtoType = weakTypeOf[Req] + val rpcRequestClosureType = weakTypeOf[RRC] + val rpcContextType = weakTypeOf[RC] + val respProtoType = weakTypeOf[Resp] + val respProtoCompanionType = weakTypeOf[Resp].companion // getDefaultInstance is static method, it's in companion val processor = q""" class $className(private val service: $serviceType, executor: java.util.concurrent.Executor = null) @@ -149,13 +149,13 @@ object ProcessorCreatorMacro { ): c.Expr[RRP] = { import c.universe._ checkTree[RRC, RRP, RC, Service](c)(needCheckService = true) - val serviceType = weakTypeOf[Service] - val className = TypeName(classNamePrefix + MacroCache.getIdentityId) - val reqProtoType = weakTypeOf[Req] - val rpcRequestClosureType = weakTypeOf[RRC] - val rpcContextType = weakTypeOf[RC] - val respProtoType = weakTypeOf[Resp] - val respProtoCompanionType = weakTypeOf[Resp].companion //getDefaultInstance is static method, it's in companion + val serviceType = weakTypeOf[Service] + val className = TypeName(classNamePrefix + MacroCache.getIdentityId) + val reqProtoType = weakTypeOf[Req] + val rpcRequestClosureType = weakTypeOf[RRC] + val rpcContextType = weakTypeOf[RC] + val respProtoType = weakTypeOf[Resp] + val respProtoCompanionType = weakTypeOf[Resp].companion // getDefaultInstance is static method, it's in companion val processor = q""" class $className(private val service: $serviceType, executor: java.util.concurrent.Executor = null) diff --git a/smt-tools/src/main/scala/org/bitlap/tools/package.scala b/smt-tools/src/main/scala/org/bitlap/tools/package.scala index 644628826315c9ab9aee6d196ccdb6347c298e95..1b632b9c162a2a7e33e2c96535897ef7a5acc748 100644 --- a/smt-tools/src/main/scala/org/bitlap/tools/package.scala +++ b/smt-tools/src/main/scala/org/bitlap/tools/package.scala @@ -21,10 +21,10 @@ package org.bitlap -/** - * @author 梦境迷离 - * @since 2021/7/7 - * @version 1.0 +/** @author + * 梦境迷离 + * @since 2021/7/7 + * @version 1.0 */ package object tools { final val PACKAGE: String = "org.bitlap.tools" diff --git a/smt-tools/src/main/scala/org/bitlap/tools/toString.scala b/smt-tools/src/main/scala/org/bitlap/tools/toString.scala index dc94c4141d9ab61bfd2cc6839bf44a56b9d70458..de02661337afb20f5055aac94865e8f7d0f01b09 100644 --- a/smt-tools/src/main/scala/org/bitlap/tools/toString.scala +++ b/smt-tools/src/main/scala/org/bitlap/tools/toString.scala @@ -25,15 +25,18 @@ import org.bitlap.tools.macros.toStringMacro import scala.annotation.{ compileTimeOnly, StaticAnnotation } -/** - * annotation to generate toString for classes. +/** annotation to generate toString for classes. * - * @author 梦境迷离 - * @param includeInternalFields Whether to include the fields defined within a class. - * @param includeFieldNames Whether to include the name of the field in the toString. - * @param callSuper Whether to include the super's toString. - * @since 2021/6/13 - * @version 1.0 + * @author + * 梦境迷离 + * @param includeInternalFields + * Whether to include the fields defined within a class. + * @param includeFieldNames + * Whether to include the name of the field in the toString. + * @param callSuper + * Whether to include the super's toString. + * @since 2021/6/13 + * @version 1.0 */ @compileTimeOnly("enable macro to expand macro annotations") final class toString( diff --git a/smt-tools/src/main/scala/org/bitlap/tools/utils/ScalaReflectionUtils.scala b/smt-tools/src/main/scala/org/bitlap/tools/utils/ScalaReflectionUtils.scala index 89d17f0386c1e62c92100ad341a9b5816bdc5f0c..1cea7d1c505214b6fdf84d76caaa8988d40096ae 100644 --- a/smt-tools/src/main/scala/org/bitlap/tools/utils/ScalaReflectionUtils.scala +++ b/smt-tools/src/main/scala/org/bitlap/tools/utils/ScalaReflectionUtils.scala @@ -24,12 +24,12 @@ package org.bitlap.tools.utils import scala.reflect.runtime.currentMirror import scala.reflect.runtime.universe._ -/** - * Scala runtime reflection +/** Scala runtime reflection * - * @author 梦境迷离 - * @since 2021/12/5 - * @version 1.0 + * @author + * 梦境迷离 + * @since 2021/12/5 + * @version 1.0 */ class ScalaReflectionUtils[T: WeakTypeTag] { diff --git a/smt-tools/src/test/scala/org/bitlap/tools/ApplyTest.scala b/smt-tools/src/test/scala/org/bitlap/tools/ApplyTest.scala index 7cc6ae67d4842336a27f6877bf0fc898948718e7..42e5b566ddd86f0178483679b95d02ef100d3306 100644 --- a/smt-tools/src/test/scala/org/bitlap/tools/ApplyTest.scala +++ b/smt-tools/src/test/scala/org/bitlap/tools/ApplyTest.scala @@ -24,10 +24,10 @@ package org.bitlap.tools import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers -/** - * @author 梦境迷离 - * @since 2021/6/30 - * @version 1.0 +/** @author + * 梦境迷离 + * @since 2021/6/30 + * @version 1.0 */ class ApplyTest extends AnyFlatSpec with Matchers { diff --git a/smt-tools/src/test/scala/org/bitlap/tools/BuilderTest.scala b/smt-tools/src/test/scala/org/bitlap/tools/BuilderTest.scala index 40a30d6151c42bdeea95bfa035f1475095bdbde9..7bcb158210243684715bce123ddccae6105b5af7 100644 --- a/smt-tools/src/test/scala/org/bitlap/tools/BuilderTest.scala +++ b/smt-tools/src/test/scala/org/bitlap/tools/BuilderTest.scala @@ -24,10 +24,10 @@ package org.bitlap.tools import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers -/** - * @author 梦境迷离 - * @since 2021/6/19 - * @version 1.0 +/** @author + * 梦境迷离 + * @since 2021/6/19 + * @version 1.0 */ class BuilderTest extends AnyFlatSpec with Matchers { @@ -51,7 +51,7 @@ class BuilderTest extends AnyFlatSpec with Matchers { } "builder3" should "class with toString, non companion object" in { - @toString //"toString" must be before "builder" + @toString // "toString" must be before "builder" @builder class TestClass1(val i: Int = 0, var j: Int, x: String, o: Option[String] = Some("")) val ret = TestClass1.builder().i(1).j(0).x("x").build() @@ -89,7 +89,7 @@ class BuilderTest extends AnyFlatSpec with Matchers { "builder7" should "case class with toString and companion object not in order" in { @builder - @toString //failed when companion object exists, fix in 0.0.6 + @toString // failed when companion object exists, fix in 0.0.6 case class TestClass1(val i: Int = 0, var j: Int, x: String, o: Option[String] = Some("")) object TestClass1 val ret = TestClass1.builder().i(1).j(0).x("x").build() diff --git a/smt-tools/src/test/scala/org/bitlap/tools/ConstructorTest.scala b/smt-tools/src/test/scala/org/bitlap/tools/ConstructorTest.scala index f65d93f375e8d5578f730e8f8088174b111f85b5..56d6c9a25b2b261fa6506309791e7dad97d173e8 100644 --- a/smt-tools/src/test/scala/org/bitlap/tools/ConstructorTest.scala +++ b/smt-tools/src/test/scala/org/bitlap/tools/ConstructorTest.scala @@ -24,10 +24,10 @@ package org.bitlap.tools import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers -/** - * @author 梦境迷离 - * @since 2021/7/3 - * @version 1.0 +/** @author + * 梦境迷离 + * @since 2021/7/3 + * @version 1.0 */ class ConstructorTest extends AnyFlatSpec with Matchers { @@ -129,8 +129,8 @@ class ConstructorTest extends AnyFlatSpec with Matchers { @builder @constructor(excludeFields = Seq("c")) class A2(int: Int, val j: Int, var k: Option[String] = None, t: Option[Long] = Some(1L)) { - private val a: Int = 1 - var b: Int = 1 + private val a: Int = 1 + var b: Int = 1 protected var c: Int = _ def helloWorld: String = "hello world" @@ -143,19 +143,14 @@ class ConstructorTest extends AnyFlatSpec with Matchers { @toString @constructor class TestClass12(val i: Int = 0)(var j: Int)(val k: Int) { - private val a: Int = 1 - var b: Int = 1 + private val a: Int = 1 + var b: Int = 1 protected var c: Int = _ } println(new TestClass12(1, 1, 1)(2)(3)) - /** - * def (i: Int, b: Int, c: Int)(j: Int)(k: Int) = { - * (i)(j)(k); - * this.b = b; - * this.c = c - * } + /** def (i: Int, b: Int, c: Int)(j: Int)(k: Int) = { (i)(j)(k); this.b = b; this.c = c } */ } @@ -166,8 +161,8 @@ class ConstructorTest extends AnyFlatSpec with Matchers { @toString @constructor class TestClass12(val i: Int = 0)(var j: Int)(val k: Int) { - var b = "hello" //primitive type, support no type declared - var c: B = new B() //not support no type declared, `var c = new B ()` cannot be compiled. + var b = "hello" // primitive type, support no type declared + var c: B = new B() // not support no type declared, `var c = new B ()` cannot be compiled. } val t = new TestClass12(1, "helloo", new B())(1)(1) println(t) diff --git a/smt-tools/src/test/scala/org/bitlap/tools/ElapsedTest.scala b/smt-tools/src/test/scala/org/bitlap/tools/ElapsedTest.scala index c27cb7f5e670b36e97d90b89f932ee1bf0d4e4f3..0238e1b79275751e07049b38d63d0bcc87429469 100644 --- a/smt-tools/src/test/scala/org/bitlap/tools/ElapsedTest.scala +++ b/smt-tools/src/test/scala/org/bitlap/tools/ElapsedTest.scala @@ -26,15 +26,15 @@ import org.scalatest.matchers.should.Matchers import scala.concurrent.Future -/** - * @author 梦境迷离 - * @since 2021/8/7 - * @version 1.0 +/** @author + * 梦境迷离 + * @since 2021/8/7 + * @version 1.0 */ class ElapsedTest extends AnyFlatSpec with Matchers { "elapsed1" should "failed, not calculate anything, the return type is not specified" in { - //Duration and TimeUnit must Full class name + // Duration and TimeUnit must Full class name """ | class A { | @elapsed(limit = scala.concurrent.duration.Duration(1, java.util.concurrent.TimeUnit.SECONDS), logLevel = org.bitlap.tools.LogLevel.INFO) @@ -63,7 +63,7 @@ class ElapsedTest extends AnyFlatSpec with Matchers { } "elapsed2" should "ok, get the returnType of the method " in { - //Duration and TimeUnit must Full class name + // Duration and TimeUnit must Full class name """ |class A { | @elapsed(limit = scala.concurrent.duration.Duration(1, java.util.concurrent.TimeUnit.NANOSECONDS), logLevel = org.bitlap.tools.LogLevel.INFO) @@ -86,7 +86,7 @@ class ElapsedTest extends AnyFlatSpec with Matchers { } "elapsed3" should "ok" in { - //Duration and TimeUnit must Full class name + // Duration and TimeUnit must Full class name """ | class A { | @elapsed(limit = scala.concurrent.duration.Duration(1, java.util.concurrent.TimeUnit.NANOSECONDS), logLevel = org.bitlap.tools.LogLevel.INFO) @@ -112,7 +112,7 @@ class ElapsedTest extends AnyFlatSpec with Matchers { } "elapsed4" should "ok, return early" in { - //Duration and TimeUnit must Full class name + // Duration and TimeUnit must Full class name """ | class A { | @elapsed(limit = scala.concurrent.duration.Duration(1, java.util.concurrent.TimeUnit.SECONDS), logLevel = org.bitlap.tools.LogLevel.INFO) @@ -210,7 +210,7 @@ class ElapsedTest extends AnyFlatSpec with Matchers { } } - "elapsed7" should "ok at object but has runTime Error" in { //Why? + "elapsed7" should "ok at object but has runTime Error" in { // Why? """ | object A { | private final val log1: org.slf4j.Logger = org.slf4j.LoggerFactory.getLogger(A.getClass) @@ -273,7 +273,7 @@ class ElapsedTest extends AnyFlatSpec with Matchers { | println("") | "hello" | } - |""".stripMargin shouldNot compile //args not in order + |""".stripMargin shouldNot compile // args not in order } "elapsed10" should "multi-return" in { class A { @@ -344,7 +344,7 @@ class ElapsedTest extends AnyFlatSpec with Matchers { val i = 0 for (i <- Seq(1)) if (i == 1) { - return 1 //not support + return 1 // not support } 0 } diff --git a/smt-tools/src/test/scala/org/bitlap/tools/EmployeeTests.scala b/smt-tools/src/test/scala/org/bitlap/tools/EmployeeTests.scala index 3b9e79fefbd7af9b6d51fb9aaad8a0b3dd8f13ad..3ebc3695e22e1615a82195dd626eda0e9ac021d9 100644 --- a/smt-tools/src/test/scala/org/bitlap/tools/EmployeeTests.scala +++ b/smt-tools/src/test/scala/org/bitlap/tools/EmployeeTests.scala @@ -33,8 +33,8 @@ class EmployeeTests extends AnyFlatSpec with Matchers { that match { case that: Employee => that.canEqual(this) && - this.role == that.role && - super.equals(that) + this.role == that.role && + super.equals(that) case _ => false } @@ -57,8 +57,8 @@ class EmployeeTests extends AnyFlatSpec with Matchers { that match { case that: Person => that.canEqual(this) && - this.name == that.name && - this.age == that.age + this.name == that.name && + this.age == that.age case _ => false } @@ -73,8 +73,8 @@ class EmployeeTests extends AnyFlatSpec with Matchers { "equals1" should "ok" in { // these first two instances should be equal - val nimoy = new Person("Leonard Nimoy", 82) - val nimoy2 = new Person("Leonard Nimoy", 82) + val nimoy = new Person("Leonard Nimoy", 82) + val nimoy2 = new Person("Leonard Nimoy", 82) val shatner = new Person("William Shatner", 82) val stewart = new Person("Patrick Stewart", 47) @@ -96,9 +96,9 @@ class EmployeeTests extends AnyFlatSpec with Matchers { "equals2" should "ok" in { // these first two instance should be equal - val eNimoy1 = new Employee("Leonard Nimoy", 82, "Actor") - val eNimoy2 = new Employee("Leonard Nimoy", 82, "Actor") - val pNimoy = new Person("Leonard Nimoy", 82) + val eNimoy1 = new Employee("Leonard Nimoy", 82, "Actor") + val eNimoy2 = new Employee("Leonard Nimoy", 82, "Actor") + val pNimoy = new Person("Leonard Nimoy", 82) val eShatner = new Employee("William Shatner", 82, "Actor") // equality tests diff --git a/smt-tools/src/test/scala/org/bitlap/tools/EqualsAndHashCodeTest.scala b/smt-tools/src/test/scala/org/bitlap/tools/EqualsAndHashCodeTest.scala index 8b5a83e5344468fa2449c138390b9c2a929f82cf..8f550e752deb52eac1282fd886ffb4d6b98ebc3d 100644 --- a/smt-tools/src/test/scala/org/bitlap/tools/EqualsAndHashCodeTest.scala +++ b/smt-tools/src/test/scala/org/bitlap/tools/EqualsAndHashCodeTest.scala @@ -24,10 +24,10 @@ package org.bitlap.tools import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers -/** - * @author 梦境迷离 - * @since 2021/7/18 - * @version 1.0 +/** @author + * 梦境迷离 + * @since 2021/7/18 + * @version 1.0 */ class EqualsAndHashCodeTest extends AnyFlatSpec with Matchers { @@ -41,8 +41,8 @@ class EqualsAndHashCodeTest extends AnyFlatSpec with Matchers { "equals1" should "ok" in { // these first two instances should be equal - val nimoy = new Person("Leonard Nimoy", 82) - val nimoy2 = new Person("Leonard Nimoy", 82) + val nimoy = new Person("Leonard Nimoy", 82) + val nimoy2 = new Person("Leonard Nimoy", 82) val shatner = new Person("William Shatner", 82) val stewart = new Person("Patrick Stewart", 47) @@ -71,9 +71,9 @@ class EqualsAndHashCodeTest extends AnyFlatSpec with Matchers { "equals2" should "ok" in { // these first two instance should be equal - val eNimoy1 = new Employee("Leonard Nimoy", 82, "Actor") - val eNimoy2 = new Employee("Leonard Nimoy", 82, "Actor") - val pNimoy = new Person("Leonard Nimoy", 82) + val eNimoy1 = new Employee("Leonard Nimoy", 82, "Actor") + val eNimoy2 = new Employee("Leonard Nimoy", 82, "Actor") + val pNimoy = new Person("Leonard Nimoy", 82) val eShatner = new Employee("William Shatner", 82, "Actor") // canEqual diff --git a/smt-tools/src/test/scala/org/bitlap/tools/JacksonEnumTest.scala b/smt-tools/src/test/scala/org/bitlap/tools/JacksonEnumTest.scala index 0699dddbb009e6af4010f163ad05b3fcb85de90a..e293282b76f36f3394fcdc63754171ebbcb35359 100644 --- a/smt-tools/src/test/scala/org/bitlap/tools/JacksonEnumTest.scala +++ b/smt-tools/src/test/scala/org/bitlap/tools/JacksonEnumTest.scala @@ -25,9 +25,9 @@ import com.fasterxml.jackson.module.scala.JsonScalaEnumeration import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers -/** - * @author 梦境迷离 - * @version 1.0,2021/8/3 +/** @author + * 梦境迷离 + * @version 1.0,2021/8/3 */ class JacksonEnumTest extends AnyFlatSpec with Matchers { diff --git a/smt-tools/src/test/scala/org/bitlap/tools/JavaCompatibleTest.scala b/smt-tools/src/test/scala/org/bitlap/tools/JavaCompatibleTest.scala index 9a8fe5be906798f00f09654aa7080eaafabade55..3a7a99adf377e327a0fe41e25256f7ea3d742f40 100644 --- a/smt-tools/src/test/scala/org/bitlap/tools/JavaCompatibleTest.scala +++ b/smt-tools/src/test/scala/org/bitlap/tools/JavaCompatibleTest.scala @@ -24,10 +24,10 @@ package org.bitlap.tools import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers -/** - * @author 梦境迷离 - * @since 2021/11/23 - * @version 1.0 +/** @author + * 梦境迷离 + * @since 2021/11/23 + * @version 1.0 */ class JavaCompatibleTest extends AnyFlatSpec with Matchers { diff --git a/smt-tools/src/test/scala/org/bitlap/tools/JsonTest.scala b/smt-tools/src/test/scala/org/bitlap/tools/JsonTest.scala index 4c5ea5f661a8b9995e3bb5079d9dea690af8a781..925c6a78d9981f3a484e7406988717e94d4b27fa 100644 --- a/smt-tools/src/test/scala/org/bitlap/tools/JsonTest.scala +++ b/smt-tools/src/test/scala/org/bitlap/tools/JsonTest.scala @@ -25,10 +25,10 @@ import play.api.libs.json.Json import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers -/** - * @author 梦境迷离 - * @since 2021/6/18 - * @version 1.0 +/** @author + * 梦境迷离 + * @since 2021/6/18 + * @version 1.0 */ class JsonTest extends AnyFlatSpec with Matchers { @@ -54,7 +54,7 @@ class JsonTest extends AnyFlatSpec with Matchers { "json2" should "println case class, no companion object" in { val json = Json.toJson(TestClass2(1, 2, "")) - val ret = Json.prettyPrint(json) + val ret = Json.prettyPrint(json) println(Json.fromJson[TestClass2](json)) println(ret) assert(ret == "{\n \"i\" : 1,\n \"j\" : 2,\n \"x\" : \"\",\n \"o\" : \"\"\n}") diff --git a/smt-tools/src/test/scala/org/bitlap/tools/LogMain.scala b/smt-tools/src/test/scala/org/bitlap/tools/LogMain.scala index 79542c3bedb1adffc13c221c6ae2a4a4da598e87..0bfed795e7f7601484a74eefd652b10ad4b01dff 100644 --- a/smt-tools/src/test/scala/org/bitlap/tools/LogMain.scala +++ b/smt-tools/src/test/scala/org/bitlap/tools/LogMain.scala @@ -21,10 +21,10 @@ package org.bitlap.tools -/** - * @author 梦境迷离 - * @since 2021/6/29 - * @version 1.0 +/** @author + * 梦境迷离 + * @since 2021/6/29 + * @version 1.0 */ object LogMain extends App { diff --git a/smt-tools/src/test/scala/org/bitlap/tools/LogTest.scala b/smt-tools/src/test/scala/org/bitlap/tools/LogTest.scala index e6d3b574d2cd85ccdb7ae16884cc0c822f8057a2..1f31edb8102feeae6d78450cc957ad9ea1fa2266 100644 --- a/smt-tools/src/test/scala/org/bitlap/tools/LogTest.scala +++ b/smt-tools/src/test/scala/org/bitlap/tools/LogTest.scala @@ -25,10 +25,10 @@ import org.bitlap.tools.logs.LogType import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers -/** - * @author 梦境迷离 - * @since 2021/6/28 - * @version 1.0 +/** @author + * 梦境迷离 + * @since 2021/6/28 + * @version 1.0 */ class LogTest extends AnyFlatSpec with Matchers { @@ -96,7 +96,7 @@ class LogTest extends AnyFlatSpec with Matchers { log.info("hello") }""" should compile - """@toString @builder @log class TestClass2(val i: Int = 0, var j: Int)""" should compile //Use with multiple annotations + """@toString @builder @log class TestClass2(val i: Int = 0, var j: Int)""" should compile // Use with multiple annotations """@log() class TestClass3(val i: Int = 0, var j: Int)""" should compile """@log class TestClass4(val i: Int = 0, var j: Int)""" should compile """@log(logType=org.bitlap.tools.logs.LogType.Slf4j) class TestClass5(val i: Int = 0, var j: Int)""" should compile @@ -110,7 +110,7 @@ class LogTest extends AnyFlatSpec with Matchers { log.info("hello") }""" should compile - """@toString @builder @log class TestClass2(val i: Int = 0, var j: Int)""" should compile //Use with multiple annotations + """@toString @builder @log class TestClass2(val i: Int = 0, var j: Int)""" should compile // Use with multiple annotations """@log() class TestClass3(val i: Int = 0, var j: Int)""" should compile """@log class TestClass4(val i: Int = 0, var j: Int)""" should compile """@log(logType=org.bitlap.tools.logs.LogType.Slf4j) class TestClass5(val i: Int = 0, var j: Int)""" should compile diff --git a/smt-tools/src/test/scala/org/bitlap/tools/NetService.scala b/smt-tools/src/test/scala/org/bitlap/tools/NetService.scala index 9947cc5a488982cac5387bcd6a10d6c9ba513c36..c0aa7d511ebb741e6ad365638439697c05cd75fb 100644 --- a/smt-tools/src/test/scala/org/bitlap/tools/NetService.scala +++ b/smt-tools/src/test/scala/org/bitlap/tools/NetService.scala @@ -21,10 +21,10 @@ package org.bitlap.tools -/** - * @author 梦境迷离 - * @since 2021/12/4 - * @version 1.0 +/** @author + * 梦境迷离 + * @since 2021/12/4 + * @version 1.0 */ class NetService { diff --git a/smt-tools/src/test/scala/org/bitlap/tools/OthersTest.scala b/smt-tools/src/test/scala/org/bitlap/tools/OthersTest.scala index bbb5bfca33b6c449f5ecca152dc1eb209af1cb5c..29d0a83ac07b0d291de18e7502ffbe154cf892a1 100644 --- a/smt-tools/src/test/scala/org/bitlap/tools/OthersTest.scala +++ b/smt-tools/src/test/scala/org/bitlap/tools/OthersTest.scala @@ -24,10 +24,10 @@ package org.bitlap.tools import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers -/** - * @author 梦境迷离 - * @since 2021/7/24 - * @version 1.0 +/** @author + * 梦境迷离 + * @since 2021/7/24 + * @version 1.0 */ class OthersTest extends AnyFlatSpec with Matchers { "others" should "ok" in { diff --git a/smt-tools/src/test/scala/org/bitlap/tools/ProcessorCreatorTest.scala b/smt-tools/src/test/scala/org/bitlap/tools/ProcessorCreatorTest.scala index 40ed12e79e3ac6cf5832767ee14c382683cca452..7b13607794e1f35b9786142fd5e97f9d34e61721 100644 --- a/smt-tools/src/test/scala/org/bitlap/tools/ProcessorCreatorTest.scala +++ b/smt-tools/src/test/scala/org/bitlap/tools/ProcessorCreatorTest.scala @@ -30,9 +30,9 @@ import org.scalatest.matchers.should.Matchers import java.util.concurrent.Executor import scala.jdk.CollectionConverters.MapHasAsScala -/** - * @author 梦境迷离 - * @version 1.0,2021/12/6 +/** @author + * 梦境迷离 + * @version 1.0,2021/12/6 */ class ProcessorCreatorTest extends AnyFlatSpec with Matchers { @@ -54,10 +54,10 @@ class ProcessorCreatorTest extends AnyFlatSpec with Matchers { ]( BOpenSessionResp.getDefaultInstance, (service, _, req) => { - val username = req.getUsername - val password = req.getPassword + val username = req.getUsername + val password = req.getPassword val configurationMap = req.getConfigurationMap - val ret = service.openSession(username, password, configurationMap.asScala.toMap) + val ret = service.openSession(username, password, configurationMap.asScala.toMap) BOpenSessionResp.newBuilder().setSessionHandle(ret).build() }, (_, _, exception) => BOpenSessionResp.newBuilder().setStatus(exception.getLocalizedMessage).build() @@ -82,10 +82,10 @@ class ProcessorCreatorTest extends AnyFlatSpec with Matchers { NetService ]( (service, _, req) => { - val username = req.getUsername - val password = req.getPassword + val username = req.getUsername + val password = req.getPassword val configurationMap = req.getConfigurationMap - val ret = service.openSession(username, password, configurationMap.asScala.toMap) + val ret = service.openSession(username, password, configurationMap.asScala.toMap) BOpenSessionResp.newBuilder().setSessionHandle(ret).build() }, (_, _, exception) => BOpenSessionResp.newBuilder().setStatus(exception.getLocalizedMessage).build() @@ -109,10 +109,10 @@ class ProcessorCreatorTest extends AnyFlatSpec with Matchers { BOpenSessionReq, BOpenSessionResp ] { (service, _, req) => - val username = req.getUsername - val password = req.getPassword + val username = req.getUsername + val password = req.getPassword val configurationMap = req.getConfigurationMap - val ret = service.openSession(username, password, configurationMap.asScala.toMap) + val ret = service.openSession(username, password, configurationMap.asScala.toMap) BOpenSessionResp.newBuilder().setSessionHandle(ret).build() } { (_, _, exception) => BOpenSessionResp.newBuilder().setStatus(exception.getLocalizedMessage).build() diff --git a/smt-tools/src/test/scala/org/bitlap/tools/ScalaReflectionUtilsTest.scala b/smt-tools/src/test/scala/org/bitlap/tools/ScalaReflectionUtilsTest.scala index 5a41364d060c687dca5bac0d0dc23f0ac9aa7dce..b8cc94b165a998100f50fbf7ae935e74ac0039ac 100644 --- a/smt-tools/src/test/scala/org/bitlap/tools/ScalaReflectionUtilsTest.scala +++ b/smt-tools/src/test/scala/org/bitlap/tools/ScalaReflectionUtilsTest.scala @@ -25,10 +25,10 @@ import org.bitlap.tools.utils.ScalaReflectionUtils import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers -/** - * @author 梦境迷离 - * @since 2021/12/5 - * @version 1.0 +/** @author + * 梦境迷离 + * @since 2021/12/5 + * @version 1.0 */ class ScalaReflectionUtilsTest extends AnyFlatSpec with Matchers { "Creator" should "ok" in { diff --git a/smt-tools/src/test/scala/org/bitlap/tools/ToStringTest.scala b/smt-tools/src/test/scala/org/bitlap/tools/ToStringTest.scala index 68fee250d2122eef0beb047c0e7d867c19b67e01..91e345c1a4f9f1fb0fa333fa89d811463edbf24f 100644 --- a/smt-tools/src/test/scala/org/bitlap/tools/ToStringTest.scala +++ b/smt-tools/src/test/scala/org/bitlap/tools/ToStringTest.scala @@ -24,16 +24,16 @@ package org.bitlap.tools import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers -/** - * @author 梦境迷离 - * @since 2021/6/13 - * @version 1.0 +/** @author + * 梦境迷离 + * @since 2021/6/13 + * @version 1.0 */ class ToStringTest extends AnyFlatSpec with Matchers { "toString1" should "not contains internal field" in { @toString(includeInternalFields = false, includeFieldNames = false, callSuper = false) class TestClass(val i: Int = 0, var j: Int) { - val y: Int = 0 + val y: Int = 0 var z: String = "hello" var x: String = "world" } @@ -45,7 +45,7 @@ class ToStringTest extends AnyFlatSpec with Matchers { "toString2" should "contains internal field and with name" in { @toString(includeInternalFields = true) class TestClass(val i: Int = 0, var j: Int) { - val y: Int = 0 + val y: Int = 0 var z: String = "hello" var x: String = "world" } @@ -57,7 +57,7 @@ class ToStringTest extends AnyFlatSpec with Matchers { "toString3" should "not contains internal field but with name" in { @toString(includeInternalFields = false, includeFieldNames = true) class TestClass(val i: Int = 0, var j: Int) { - val y: Int = 0 + val y: Int = 0 var z: String = "hello" var x: String = "world" } @@ -69,7 +69,7 @@ class ToStringTest extends AnyFlatSpec with Matchers { "toString4" should "contains internal field but without name" in { @toString(includeInternalFields = true, includeFieldNames = false) class TestClass(val i: Int = 0, var j: Int) { - val y: Int = 0 + val y: Int = 0 var z: String = "hello" var x: String = "world" } @@ -81,7 +81,7 @@ class ToStringTest extends AnyFlatSpec with Matchers { "toString5" should "case class without name" in { @toString(includeInternalFields = false, includeFieldNames = false) case class TestClass(i: Int = 0, var j: Int) { - val y: Int = 0 + val y: Int = 0 var z: String = "hello" var x: String = "world" } @@ -93,12 +93,12 @@ class ToStringTest extends AnyFlatSpec with Matchers { "toString6" should "case class not contains internal field and with name" in { @toString(includeInternalFields = false, includeFieldNames = true) case class TestClass(i: Int = 0, var j: Int) { - val y: Int = 0 + val y: Int = 0 var z: String = "hello" var x: String = "world" } case class TestClass2(i: Int = 0, var j: Int) // No method body, use default toString - val s = TestClass(1, 2).toString + val s = TestClass(1, 2).toString val s2 = TestClass2(1, 2).toString println(s) println(s2) @@ -110,7 +110,7 @@ class ToStringTest extends AnyFlatSpec with Matchers { "toString7" should "case class contains internal field and with name" in { @toString(includeFieldNames = true) case class TestClass(i: Int = 0, var j: Int) { - val y: Int = 0 + val y: Int = 0 var z: String = "hello" var x: String = "world" } @@ -122,7 +122,7 @@ class ToStringTest extends AnyFlatSpec with Matchers { "toString8" should "case class contains internal field and with name, itself" in { @toString(includeInternalFields = true, includeFieldNames = true) case class TestClass(i: Int = 0, var j: Int, k: TestClass) { - val y: Int = 0 + val y: Int = 0 var z: String = "hello" var x: String = "world" } @@ -134,9 +134,9 @@ class ToStringTest extends AnyFlatSpec with Matchers { "toString9" should "case class contains internal field and with name, itself2" in { @toString(includeInternalFields = true, includeFieldNames = true) case class TestClass(i: Int = 0, var j: Int) { - val y: Int = 0 - var z: String = "hello" - var x: String = "world" + val y: Int = 0 + var z: String = "hello" + var x: String = "world" val t: TestClass = null // if not null, will error } val s = TestClass(1, 2).toString @@ -147,7 +147,7 @@ class ToStringTest extends AnyFlatSpec with Matchers { "toString10" should "case class contains internal field with name, itself3" in { @toString(includeInternalFields = true, includeFieldNames = true) case class TestClass(i: Int = 0, var j: Int, k: TestClass) { - val y: Int = 0 + val y: Int = 0 var z: String = "hello" var x: String = "world" }