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

Add SplitByTypes observables #116

Merged
merged 13 commits into from
Nov 9, 2024
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
package com.raquo.airstream.split

import scala.quoted.{Expr, Quotes, Type}

private[split] object MacrosUtilities {

def exprOfListToListOfExpr[T: Type](
pfListExpr: Expr[List[T]]
)(
using quotes: Quotes
): List[Expr[T]] = {
import quotes.reflect.*

pfListExpr match {
case '{ $headExpr :: (${ tailExpr }: List[T]) } =>
headExpr :: exprOfListToListOfExpr(tailExpr)
case '{ Nil } => Nil
case _ =>
report.errorAndAbort(
"Macro expansion failed, please use `handleCase` instead"
)
}

}

def listOfExprToExprOfList[T: Type](
pfExprList: List[Expr[T]]
)(
using quotes: Quotes
): Expr[List[T]] = {
import quotes.reflect.*

pfExprList match
case head :: tail => '{ $head :: ${ listOfExprToExprOfList(tail) } }
case Nil => '{ Nil }
}

def innerObservableImpl[I: Type](
iExpr: Expr[I],
caseListExpr: Expr[List[PartialFunction[Any, Any]]]
)(
using quotes: Quotes
): Expr[(Int, Any)] = {
import quotes.reflect.*

val caseExprList = exprOfListToListOfExpr(caseListExpr)

val allCaseDefLists = caseExprList.reverse.zipWithIndex
.flatMap { case (caseExpr, idx) =>
caseExpr.asTerm match {
case Lambda(_, Match(_, caseDefList)) => {
caseDefList.map { caseDef =>
val idxExpr = Expr.apply(idx)
val newRhsExpr = '{
val res = ${ caseDef.rhs.asExprOf[Any] }; ($idxExpr, res)
}
CaseDef.copy(caseDef)(
caseDef.pattern,
caseDef.guard,
newRhsExpr.asTerm
)
}
}
case _ =>
report.errorAndAbort(
"Macro expansion failed, please use `handleCase` with annonymous partial function"
)
}
}
.map(_.changeOwner(Symbol.spliceOwner))

Match(iExpr.asTerm, allCaseDefLists).asExprOf[(Int, Any)]
}

object ShowType {
def nameOfExpr[CC[_]](using Type[CC], Quotes): Expr[String] = Expr(Type.show[CC])
inline def nameOf[CC[_]] = ${ nameOfExpr[CC] }
}

}
Loading