--- a/solutions/cw4/parser.sc Wed May 29 13:25:30 2024 +0100
+++ b/solutions/cw4/parser.sc Thu Sep 19 15:47:33 2024 +0100
@@ -1,13 +1,14 @@
// CW3
-import $file.lexer
-import lexer._
+import scala.language.implicitConversions
+
+import $file.lexer, lexer._
case class ~[+A, +B](x: A, y: B)
// parser combinators
-abstract class Parser[I, T](using is: I => Seq[_]) {
+abstract class Parser[I, T](using is: I => Seq[?]) {
def parse(in: I): Set[(T, I)]
def parse_all(in: I) : Set[T] =
@@ -17,13 +18,13 @@
// alternative parser
class AltParser[I, T](p: => Parser[I, T],
- q: => Parser[I, T])(using I => Seq[_]) extends Parser[I, T] {
+ q: => Parser[I, T])(using I => Seq[?]) extends Parser[I, T] {
def parse(in: I) = p.parse(in) ++ q.parse(in)
}
// sequence parser
class SeqParser[I, T, S](p: => Parser[I, T],
- q: => Parser[I, S])(using I => Seq[_]) extends Parser[I, ~[T, S]] {
+ q: => Parser[I, S])(using I => Seq[?]) extends Parser[I, ~[T, S]] {
def parse(in: I) =
for ((hd1, tl1) <- p.parse(in);
(hd2, tl2) <- q.parse(tl1)) yield (new ~(hd1, hd2), tl2)
@@ -31,14 +32,14 @@
// map parser
class MapParser[I, T, S](p: => Parser[I, T],
- f: T => S)(using I => Seq[_]) extends Parser[I, S] {
+ f: T => S)(using I => Seq[?]) extends Parser[I, S] {
def parse(in: I) = for ((hd, tl) <- p.parse(in)) yield (f(hd), tl)
}
// more convenient syntax for parser combinators
-extension [I, T](p: Parser[I, T])(using I => Seq[_]) {
+extension [I, T](p: Parser[I, T])(using I => Seq[?]) {
def ||(q : => Parser[I, T]) = new AltParser[I, T](p, q)
- def ~[S] (q : => Parser[I, S]) = new SeqParser[I, T, S](p, q)
+ def ~[S] (q : => Parser[I, S])(using S => Seq[?]) = new SeqParser[I, T, S](p, q)
def map[S](f: => T => S) = new MapParser[I, T, S](p, f)
}
@@ -71,16 +72,18 @@
// Implicit definitions to go from a token
// or a list of tokens to a TokenListParser
-implicit def token2parser(t: Token) : Parser[List[Token], Token] =
- TokenParser(t)
+given Conversion[Token, Parser[List[Token], Token]] = (t => TokenParser(t))
+//implicit def token2parser(t: Token) : Parser[List[Token], Token] =
+// TokenParser(t)
+/*
extension (t: Token) {
def || (q : => Parser[List[Token], Token]) =
new AltParser[List[Token], Token](t, q)
def ~[S](q : => Parser[List[Token], S]) =
new SeqParser[List[Token], Token, S](t, q)
}
-
+*/
// Abstract Syntax Trees