Interpret match expressions

This commit is contained in:
Scott Richmond 2022-03-20 14:14:15 -04:00
parent 069e3b4a7b
commit 11a51cf708
2 changed files with 38 additions and 8 deletions

View File

@ -97,6 +97,30 @@
(interpret else-expr ctx)
)))
(defn- interpret-match [ast ctx]
(let [match-expr (:expr ast)
expr (interpret match-expr ctx)
clauses (:clauses ast)]
(loop [clause (first clauses)
clauses (rest clauses)]
(if clause
(let [pattern (:pattern clause)
body (:body clause)
new-ctx (atom {::parent ctx})
match? (match pattern expr new-ctx)
success (:success match?)
clause-ctx (:ctx match?)]
(if success
(do
(swap! new-ctx #(merge % clause-ctx))
(interpret body new-ctx))
(recur (first clauses) (rest clauses))
))
(throw (ex-info "Match Error: No match found" {}))
))
)
)
(defn interpret [ast ctx]
(case (::ast/type ast)
@ -108,6 +132,8 @@
::ast/if (interpret-if ast ctx)
::ast/match (interpret-match ast ctx)
::ast/block
(let [exprs (:exprs ast)
inner (pop exprs)
@ -154,8 +180,12 @@
(do
(def source "
let (foo, (_, baz)) = (1, (2, 3))
baz
let foo = (1, 2)
match foo with {
0 -> :zero
(_, 3) -> :one
& baz -> baz
}
")
(println "")

View File

@ -466,7 +466,7 @@
(let [curr (current parser)]
(case (::token/type curr)
::token/rbrace
(assoc parser ::ast {::ast/type ::ast/clauses :clauses clauses})
(assoc (advance parser) ::ast {::ast/type ::ast/clauses :clauses clauses})
::token/newline
(recur (accept-many #{::token/newline} parser) clauses)
@ -566,10 +566,10 @@
(do
(def pp pp/pprint)
(def source "match foo with {
_ -> foo
foo () -> bar
() -> baz
}")
0 -> foo
}
")
(def lexed (scanner/scan source))
(def tokens (:tokens lexed))
(def p (parser tokens))
@ -581,7 +581,7 @@
(println "*** *** NEW PARSE *** ***")
(-> p
(parse-match)
(parse-script)
(::ast)
(pp)
)