Skip to content

Commit

Permalink
expand selector demo to account for unions
Browse files Browse the repository at this point in the history
  • Loading branch information
kubukoz committed Nov 11, 2024
1 parent 7629f98 commit c4bce3a
Showing 1 changed file with 54 additions and 4 deletions.
58 changes: 54 additions & 4 deletions modules/parser-gen/src/main/scala/playground/parsergen/demo.scala
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
case class Foo(bars: List[Bar]) {
case class Foo(bars: List[Bar], nodes: List[Node]) {
def select[A](f: Foo.Selector => Selection[A]): List[A] = f(Foo.Selector(List(this))).path
}

object Foo {

case class Selector(path: List[Foo]) extends Selection[Foo] {
def bars: Bar.Selector = Bar.Selector(path.flatMap(_.bars))
def nodes: Node.Selector = Node.Selector(path.flatMap(_.nodes))
}

}
Expand Down Expand Up @@ -38,15 +39,64 @@ object Identifier {
case class Selector(path: List[Identifier]) extends Selection[Identifier]
}

enum Node {
case Ident(i: Identifier)
case B(b: Baz)

def asIdent: Option[Identifier] =
this match {
case Ident(i) => Some(i)
case _ => None
}

def asB: Option[Baz] =
this match {
case B(b) => Some(b)
case _ => None
}

}

object Node {

case class Selector(val path: List[Node]) extends Selection[Node] {
def ident: Identifier.Selector = Identifier.Selector(path.flatMap(_.asIdent))
def b: Baz.Selector = Baz.Selector(path.flatMap(_.asB))
}

}

trait Selection[A] {
def path: List[A]
}

@main def demo = {
import util.chaining.*

Foo(List(Bar(Some(Baz(List("a", "b").map(Identifier.apply)))))).select(_.bars.baz).pipe(println)
Foo(List(Bar(Some(Baz(List("a", "b").map(Identifier.apply))))))
.select(_.bars.baz.names)
Foo(
List(Bar(Some(Baz(List("a", "b").map(Identifier.apply))))),
List(Node.Ident(Identifier("aa"))),
).select(_.bars.baz).pipe(println)

println(
Foo(
List(Bar(Some(Baz(List("a", "b").map(Identifier.apply))))),
List(Node.Ident(Identifier("aa"))),
)
.select(_.bars.baz.names) ==
Foo(
List(Bar(Some(Baz(List("a", "b").map(Identifier.apply))))),
List(Node.Ident(Identifier("aa"))),
)
.select(_.bars.baz)
.flatMap(_.names)
)

Foo(
List(Bar(Some(Baz(List("a", "b").map(Identifier.apply))))),
List(Node.Ident(Identifier("aa"))),
)
.select(_.nodes.ident)
// .select(_.nodes.b.names)
.pipe(println)
}

0 comments on commit c4bce3a

Please sign in to comment.