Created
July 31, 2019 14:22
-
-
Save dharasim/224917c5103ecf7958f69c3ae463e3a5 to your computer and use it in GitHub Desktop.
Using parser combinators in Julia https://github.com/wdebeaum/PEG.jl
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module TreeFromString | |
using PEG | |
import Base: show | |
struct Tree{T} | |
val ::T | |
children ::Vector{Tree{T}} | |
end | |
isterminal(t::Tree) = isempty(t.children) | |
function show(io::IO, t::Tree) | |
if isterminal(t) | |
print(io, t.val, ' ') | |
else | |
print(io, "[.", t.val, ' ') | |
foreach(t -> print(io, t), t.children) | |
print(io, ']') | |
end | |
end | |
@rule token = r"[^\[\] ]*" & " " > | |
(terminal, space) -> Tree{String}(terminal, String[]) | |
@rule nonterminal = "[." & r"[^\[\] ]*" & " " & tree[+] & "]" > | |
(open, nonterminal, space, children, close) -> Tree{String}(nonterminal, children) | |
@rule tree = nonterminal, token | |
let str = "[.C [.D1 D2 ] E ]" | |
@assert string(tree(str)[1]) == str | |
end | |
end # module |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment