Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Magnolia fastparse #2

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 11 additions & 7 deletions build.sbt
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ enablePlugins(TutPlugin)
enablePlugins(LaikaPlugin)

val sharedSettings = Seq(
scalaVersion := "2.12.6",
scalaVersion := "2.12.8",
scalacOptions ++= Seq( // from: https://tpolecat.github.io/2017/04/25/scalac-flags.html
"-deprecation", // Emit warning and location for usages of deprecated APIs.
"-encoding",
Expand Down Expand Up @@ -63,7 +63,7 @@ organization := "com.github.aborg0"

version := "0.1"

scalaVersion := "2.12.6"
scalaVersion := "2.12.8"

startYear := Some(2018)

Expand Down Expand Up @@ -92,14 +92,18 @@ lazy val caseyClassyJVM = caseyClassy.jvm.enablePlugins(SbtOsgi)

//lazy val caseyClassyNative = caseyClassy.native

libraryDependencies += "org.scalactic" %% "scalactic" % "3.0.5"
libraryDependencies += "org.scalatest" %% "scalatest" % "3.0.5" % "test"
libraryDependencies += "org.scalactic" %% "scalactic" % "3.1.0"
libraryDependencies += "org.scalatest" %% "scalatest" % "3.1.0" % "test"

resolvers ++= Seq(
Resolver.sonatypeRepo("releases"),
Resolver.sonatypeRepo("snapshots")
)

libraryDependencies ++= Seq(
"com.chuusai" %%% "shapeless" % "2.3.3"
)
//libraryDependencies ++= Seq(
// "com.chuusai" %%% "shapeless" % "2.3.3"
//)

libraryDependencies += "com.lihaoyi" %%% "fastparse" % "1.0.1"

libraryDependencies += "com.propensive" %%% "magnolia" % "0.7.1"
2 changes: 1 addition & 1 deletion project/build.properties
Original file line number Diff line number Diff line change
@@ -1 +1 @@
sbt.version=1.1.6
sbt.version=1.3.8
19 changes: 10 additions & 9 deletions project/plugins.sbt
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
addSbtPlugin("org.scala-js" % "sbt-scalajs" % "0.6.23")
addSbtPlugin("org.portable-scala" % "sbt-crossproject" % "0.4.0") // (1)
addSbtPlugin("org.portable-scala" % "sbt-scalajs-crossproject" % "0.4.0") // (2)
//addSbtPlugin("org.scala-js" % "sbt-scalajs" % "0.6.32")
addSbtPlugin("org.scala-js" % "sbt-scalajs" % "1.0.0")
addSbtPlugin("org.portable-scala" % "sbt-crossproject" % "1.0.0") // (1)
addSbtPlugin("org.portable-scala" % "sbt-scalajs-crossproject" % "1.0.0") // (2)
addSbtPlugin("org.scala-native" % "sbt-scala-native" % "0.3.7") // (3)
addSbtPlugin("org.tpolecat" % "tut-plugin" % "0.6.3")
addSbtPlugin("org.tpolecat" % "tut-plugin" % "0.6.12")
//addSbtPlugin("com.artima.supersafe" % "sbtplugin" % "1.1.5")
addSbtPlugin("org.planet42" % "laika-sbt" % "0.7.5")
addSbtPlugin("org.scoverage" % "sbt-scoverage" % "1.5.1")
addSbtPlugin("org.scoverage" % "sbt-coveralls" % "1.2.4")
addSbtPlugin("com.geirsson" % "sbt-scalafmt" % "1.4.0")
addSbtPlugin("com.typesafe.sbt" % "sbt-osgi" % "0.9.3")
addSbtPlugin("org.planet42" % "laika-sbt" % "0.11.0")
addSbtPlugin("org.scoverage" % "sbt-scoverage" % "1.6.0")
addSbtPlugin("org.scoverage" % "sbt-coveralls" % "1.2.7")
addSbtPlugin("org.scalameta" % "sbt-scalafmt" % "2.0.0")
addSbtPlugin("com.typesafe.sbt" % "sbt-osgi" % "0.9.5")
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
package com.github.aborg0.caseyclassy

import fastparse.all._
import java.time.{LocalDate, LocalTime}

import fastparse.core

import language.experimental.macros
import magnolia._

import scala.reflect.runtime.universe._

private[caseyclassy] trait FPMagnoliaImplementations {
implicit def booleanParse: FastParseParse[Boolean] = () => P("true" | "false").!.map(_.toBoolean)

private[this] def integral: Parser[String] = P("-".? ~ CharIn('0' to '9').rep(1)).!

private[this] def numeric: Parser[String] = P("NaN" | "-".? ~ "Infinity" |
("-".? ~ CharIn('0' to '9').rep(1) ~
("." ~/ CharIn('0' to '9').rep(1)).? ~
(CharIn("eE") ~/ CharIn("+-").? ~/ CharIn('0' to '9').rep(1)).?)).!

implicit def longParse: FastParseParse[Long] = () => integral.map(_.toLong)

implicit def intParse: FastParseParse[Int] = () => integral.map(_.toInt)

implicit def shortParse: FastParseParse[Short] = () => integral.map(_.toShort)

implicit def byteParse: FastParseParse[Byte] = () => integral.map(_.toByte)

implicit def doubleParse: FastParseParse[Double] = () => numeric.!.map(_.toDouble)

implicit def floatParse: FastParseParse[Float] = () => numeric.!.map(_.toFloat)

// implicit def parseHNil: FastParseParse[HNil] = () => Pass.map(_ => HNil)
//
// implicit def parseCNil: FastParseParse[CNil] = () => Fail.log("CNil")
//
// implicit def parseProduct[Head, Tail <: HList](implicit headParse: Lazy[FastParseParse[Head]],
// tailParse: Lazy[FastParseParse[Tail]]): FastParseParse[Head :: Tail] =
// () => (headParse.value.parser() ~ ",".? ~ tailParse.value.parser()).map { case (h, t) => h :: t }
//
// implicit def parseCoproduct[Head, Tail <: Coproduct](implicit headParse: Lazy[FastParseParse[Head]],
// tailParse: Lazy[FastParseParse[Tail]]): FastParseParse[Head :+: Tail] =
// () => headParse.value.parser().map(Inl(_)) | tailParse.value.parser().map(Inr(_))
//
// implicit def generic[A: TypeTag, R](implicit gen: Generic.Aux[A, R], argParse: FastParseParse[R]): FastParseParse[A] = () => {
// val typeKind = implicitly[TypeTag[A]]
// if (typeKind.tpe.typeSymbol.isAbstract /* Approximation of sealed trait */ ) argParse.parser().map(gen.from) else {
// val name = typeKind.tpe.typeSymbol.name.toString
// if (name.startsWith("Tuple"))
// P("(" ~/ argParse.parser() ~ ")").map(gen.from)
// else
// P(name ~ (("(" ~/ argParse.parser() ~ ")") | argParse.parser())).map(gen.from)
// }
// }
}

case object FastParseMagnoliaParseCaseClass extends MagnoliaParseCaseClass with FPMagnoliaImplementations {
type Typeclass[T] = FastParseParse[T]

def combine[T](ctx: CaseClass[FastParseParse, T]): FastParseParse[T] = () => {
val typeKind = ctx.typeName
val typeName = typeKind.short
if (ctx.isObject) {
P(typeName).map(_ => ctx.rawConstruct(Seq.empty))
} else {
P((if (typeName.startsWith("Tuple")) Pass else P(typeName)) ~ "(" ~
// val argsParser = ctx.parameters.map(param => param.typeclass.parser() ~ ",".?)
//ctx.rawConstruct(argsParser)
// ctx.parameters.map(p => p.typeclass.parser()).map(v => v: Parser[Any])
// .reduce((p1, p2) => p1.! ~",".? ~ p2.!)
sequence(ctx.parameters.map(_.typeclass.parser().map(v=> v: Any)), ",").map(seq => ctx.rawConstruct(seq)) ~ ")"
)
// ctx.parameters.foldLeft(Pass: Parser[Any])((parser, param) => parser ~ ",".? ~ param.typeclass.parser())
// ~ ")").map(params => ctx.rawConstruct(params.asInstanceOf[Seq[Any]]))
}
// def show(value: T): String = ctx.parameters.map { p =>
// s"${p.label}=${p.typeclass.show(p.dereference(value))}"
// }.mkString("{", ",", "}")
}

def dispatch[T](ctx: SealedTrait[FastParseParse, T]): FastParseParse[T] = new FastParseParse[T] {
override def parser(): Parser[T] = {
ctx.subtypes.map(_.typeclass.parser()).reduce[Parser[T]]((p1, p2) => p1 | p2)
// def show(value: T): String = ctx.dispatch(value) { sub =>
// sub.typeclass.show(sub.cast(value))
// }
}
}

implicit def gen[T]: FastParseParse[T] = macro Magnolia.gen[T]

override def to[A](input: String)(implicit parse: Parse[A]): A = {
parse.parse(input)
}

def apply[A](implicit p: FastParseParse[A]): FastParseParse[A] = p

//region Custom overrides of special types
implicit def stringParse: FastParseParse[String] = () =>
P(CharsWhile(c => c != ',' && c != ')').!) | P("").!

implicit def timeParse: FastParseParse[LocalTime] = () => P(
CharIn('0' to '9').rep(2, "", 2) ~ ":" ~
CharIn('0' to '9').rep(2, "", 2) ~
(":" ~/ CharIn('0' to '9').rep(2, "", 2) ~
("." ~/ CharIn('0' to '9').rep(1)).?).?).!.map(LocalTime.parse(_))

implicit def dateParse: FastParseParse[LocalDate] = () =>
P(CharIn('0' to '9').rep(4, "", 4) ~ "-" ~
CharIn('0' to '9').rep(1, "", 2) ~ "-" ~
CharIn('0' to '9').rep(1, "", 2)).!.map(LocalDate.parse(_))

implicit def seqConverter[A](implicit parseA: FastParseParse[A]): FastParseParse[Seq[A]] = () =>
P(("WrappedArray" | "List" | "Vector") ~ "(" ~/ parseA.parser().rep(sep = ", ") ~ ")")

//endregion
}

trait MagnoliaParseCaseClass {
def to[A /*<: AnyRef*/](input: String)(implicit parse: Parse[A]): A
}

trait FastParseParse[A] extends Parse[A] {
protected[caseyclassy] def parser(): Parser[A]

override def parse(input: String): A = parser().parse(input).fold((p, i, e) =>
throw new IllegalArgumentException(s"Expected: $p at position: $i"), (a, i) => a)
}
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
package com.github.aborg0.caseyclassy

import shapeless.Lazy
//import shapeless.Lazy

trait ParseCaseClass {
def to[A <: AnyRef](input: String)(implicit parse: Lazy[Parse[A]]): A
}
//trait ParseCaseClass {
// def to[A /*<: AnyRef*/](input: String)(implicit parse: Lazy[Parse[A]]): A
//}

trait Parse[A] {
def parse(input: String): A
Expand Down
Loading