From 9219068a8680d3b7fc8c89bd14f81b094423f5a2 Mon Sep 17 00:00:00 2001 From: Tan Kian-ting Date: Tue, 5 Aug 2025 21:55:40 +0800 Subject: [PATCH] add combinator --- src/parser.jl | 83 +++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 80 insertions(+), 3 deletions(-) diff --git a/src/parser.jl b/src/parser.jl index 537585a..7578b31 100644 --- a/src/parser.jl +++ b/src/parser.jl @@ -1,5 +1,77 @@ module Parser +struct ParserResult + matched + remained +end + +OptParserResult = Union{Nothing,ParserResult} + +struct Psr + fun +end + +function strng(c) + return Psr((x)-> length(x) >= 1 ? + (x[1][1] == c ? + ParserResult([x[1]], x[2:end]) + : nothing) + : nothing) +end + +function type(t) + return Psr((x)-> length(x) >= 1 ? + (x[1][2] == t ? + ParserResult([x[1]], x[2:end]) + : nothing) + : nothing) +end + +(>>)(a::OptParserResult, b::Psr) = then(a, b) + +function then(a, b) + if a == nothing + return a + else + return b.fun(a.remained) + end +end + +(|)(a::Psr, b::Psr) = choice(a, b) + +function choice(a, b) + return Psr((x)-> (a.fun(x) == nothing ? b.fun(x) : a.fun(x))) +end + + + +function seq(parserLst) + function seqAux(s) + result = [] + isNothing = false + tmp = nothing + + for p in parserLst + println("s+=+=", s) + tmp = p.fun(s) + println("tmp%%%%", tmp) + if tmp == nothing + return nothing + else + s = tmp.remained) + push!(result, tmp.matched) + + end + end + + return ParserResult(result, s) + end + + return Psr(seqAux) +end + + + patternList = [("int", "\\d+"), ("id", "[_a-zA-Z][_0-9a-zA-Z]*"), ("l_paren", "[\\(]"), @@ -53,12 +125,17 @@ matchedList = map((x)->x.match, collect(mI)) groupNameList = map(processKeys, collect(mI)) -list1 = [1, 2, 3] -list2 = ["a", "b", "c"] - zippedTokenList = collect(zip(matchedList, groupNameList)) print(zippedTokenList) +withoutSpaces = filter((x)-> x[2] != "sp", zippedTokenList) +initWrapped = ParserResult([], withoutSpaces) + + +println(initWrapped >> strng("123") >> (strng("+")|strng("-"))) +println(initWrapped >> seq([strng("123"), strng("+")])) + + end