Continuations

This commit is contained in:
Tibo De Peuter 2025-05-09 14:02:03 +02:00
parent 88c90220fe
commit 026218ddbd
Signed by: tdpeuter
GPG key ID: 38297DE43F75FFE2
13 changed files with 255 additions and 15 deletions

View file

@ -3,9 +3,10 @@ package parser.grammars
import com.github.h0tk3y.betterParse.combinators.*
import com.github.h0tk3y.betterParse.grammar.parser
import com.github.h0tk3y.betterParse.parser.Parser
import com.github.h0tk3y.betterParse.utils.Tuple2
import prolog.ast.arithmetic.Float
import prolog.ast.arithmetic.Integer
import prolog.ast.lists.List
import prolog.ast.lists.List as PList
import prolog.ast.terms.*
import prolog.builtins.Dynamic
import prolog.ast.lists.List.Empty
@ -96,14 +97,19 @@ open class TermsGrammar : Tokens() {
if (t2 == null) t1 else CompoundTerm(Atom(t2!!.t1), listOf(t1, t2!!.t2))
}
protected val not: Parser<Term> by (notOp * parser(::term900)) use {
CompoundTerm(Atom(t1.text), listOf(t2))
}
protected val term900: Parser<Term> by (not or term700)
protected val op1000: Parser<String> by (comma) use { text }
protected val term1000: Parser<Term> by (term700 * zeroOrMore(op1000 * term700)) use {
t2.fold(t1) { acc, (op, term) -> CompoundTerm(Atom(op), listOf(acc, term)) }
protected val term1000: Parser<Term> by (term900 * zeroOrMore(op1000 * term900)) use {
constructRightAssociative(t1, t2)
}
protected val op1100: Parser<String> by (semicolon) use { text }
protected val term1100: Parser<Term> by (term1000 * zeroOrMore(op1100 * term1000)) use {
t2.fold(t1) { acc, (op, term) -> CompoundTerm(Atom(op), listOf(acc, term)) }
constructRightAssociative(t1, t2)
}
protected val dynamic: Parser<Term> by (dynamicOp * functor) use {
@ -117,12 +123,12 @@ open class TermsGrammar : Tokens() {
}
// Lists
protected val list: Parser<List> by (-leftBracket * separated(
protected val list: Parser<PList> by (-leftBracket * separated(
parser(::termNoConjunction),
comma,
acceptZero = true
) * -rightBracket) use {
var list: List = Empty
var list: PList = Empty
// Construct the list in reverse order
for (term in this.terms.reversed()) {
list = Cons(term, list)
@ -139,4 +145,12 @@ open class TermsGrammar : Tokens() {
protected val body: Parser<Body> by term use { this as Body }
override val rootParser: Parser<Any> by term
fun constructRightAssociative(left: Term, pairs: List<Tuple2<String, Term>>): Term {
if (pairs.isEmpty()) return left
val (name, next) = pairs.first()
val remainingPairs = pairs.drop(1)
return CompoundTerm(Atom(name), listOf(left, constructRightAssociative(next, remainingPairs)))
}
}

View file

@ -21,6 +21,8 @@ abstract class Tokens : Grammar<Any>() {
protected val semicolon: Token by literalToken(";")
// 1000
protected val comma: Token by literalToken(",")
// 900
protected val notOp: Token by literalToken("\\+")
// 700
protected val univOp: Token by literalToken("=..")
protected val notEquivalent: Token by literalToken("\\==")