1
1
mirror of https://github.com/kanaka/mal.git synced 2024-10-04 01:17:33 +03:00
mal/process/step9_try.txt
Nicolas Boulenguez 033892777a Merge eval-ast and macro expansion into EVAL, add DEBUG-EVAL
See issue #587.
* Merge eval-ast and eval into a single conditional.
* Expand macros during the apply phase, removing lots of duplicate
  tests, and increasing the overall consistency by allowing the macro
  to be computed instead of referenced by name (`((defmacro! cond
  (...)))` is currently illegal for example).
* Print "EVAL: $ast" at the top of EVAL if DEBUG-EVAL exists in the
  MAL environment.
* Remove macroexpand and quasiquoteexpand special forms.
* Use pattern-matching style in process/step*.txt.

Unresolved issues:
c.2: unable to reproduce with gcc 11.12.0.
elm: the directory is unchanged.
groovy: sometimes fail, but not on each rebuild.
nasm: fails some new soft tests, but the issue is unreproducible when
  running the interpreter manually.
objpascal: unreproducible with fpc 3.2.2.
ocaml: unreproducible with 4.11.1.
perl6: unreproducible with rakudo 2021.09.

Unrelated changes:
Reduce diff betweens steps.
Prevent defmacro! from mutating functions: c forth logo miniMAL vb.
dart: fix recent errors and warnings
ocaml: remove metadata from symbols.

Improve the logo implementation.
Encapsulate all representation in types.lg and env.lg, unwrap numbers.
Replace some manual iterations with logo control structures.
Reduce the diff between steps.
Use native iteration in env_get and env_map
Rewrite the reader with less temporary strings.
Reduce the number of temporary lists (for example, reverse iteration
with butlast requires O(n^2) allocations).
It seems possible to remove a few exceptions: GC settings
(Dockerfile), NO_SELF_HOSTING (IMPLS.yml) and step5_EXCLUDES
(Makefile.impls) .
2024-08-05 11:40:49 -05:00

137 lines
5.0 KiB
Plaintext

--- step9_try -----------------------------------
import types, reader, printer, env, core
READ(str): return reader.read_str(str)
quasiquote(ast): return ... // quasiquote
EVAL(ast, env):
loop:
if env.get('DEBUG-EVAL) exists and not in nil, false then prn('EVAL ast)
match ast:
'key: return env.get(key) or raise "'{key}' not found"
[form1 ..]: return [EVAL(form1, env) ..]
{key1 value1 ..}: return {key1 EVAL(value1, env) ..}
('def! 'key value): return env.set(key, EVAL(value, env))
('let* (k1 v1 ..) form): env = new Env(env)
env.set(k1, EVAL(v1, env))
..
ast = form; continue
('let* [k1 v1 ..] form): // idem
('do form1 .. last): EVAL(form1, env)
..
ast = last; continue
('if cond yes no): if EVAL(cond, env) in nil, false
then ast = yes; continue
else ast = no; continue
('if cond yes): // idem with return nil in the else branch
('fn* ('key1 ..) impl): return new MalFn(env, impl, parm=[key1 ..])
('fn* ['key1 ..] impl): // idem
('quote form): return form
('quasiquote form): ast = quasiquote(form); continue
('defmacro! 'key value): return env.set(key, as_macro(EVAL(value, env)))
('try* f ('catch* 'k h)): try returning EVAL(f, env)
if native or malval exception then:
env = new Env(env)
env.set(k, exception)
ast = h; continue
('try* form): ast = form; continue
(callable arg1 ..): f = EVAL(callable, env)
if macro?(f) then:
ast = f(arg1, ..); continue
args = [EVAL(arg1, env) ..]
if malfn?(f) then:
env = new Env(f.env, f.parm, args)
ast = f.impl; continue
return f(args)
otherwise: return ast
PRINT(exp): return printer.pr_str(exp)
repl_env = new Env()
rep(str): return PRINT(EVAL(READ(str),repl_env))
;; core.EXT: defined using the host language.
core.ns.map((k,v) -> (repl_env.set(k, v)))
repl_env.set('eval, (ast) -> EVAL(ast, repl-env))
repl_env.set('*ARGV*, cmdline_args[1..])
;; core.mal: defined using the language itself
rep("(def! not (fn* (a) (if a false true)))")
rep("(def! load-file (fn* (f) (eval (read-string (str \"(do \" (slurp f) \"\nnil)\")))))")
rep("(defmacro! cond (fn* (& xs) (if (> (count xs) 0) (list 'if (first xs) (if (> (count xs) 1) (nth xs 1) (throw \"odd number of forms to cond\")) (cons 'cond (rest (rest xs)))))))");
if cmdline_args: rep("(load-file \"" + args[0] + "\")"); exit 0
main loop:
try: println(rep(readline("user> ")))
catch e: println("Error: ", e)
--- env module ----------------------------------
class Env (outer=null,binds=[],exprs=[])
data = hash_map()
foreach b, i in binds:
if binds[i] == '&: data[binds[i+1]] = exprs.drop(i); break
else: data[binds[i]] = exprs[i]
set(k,v): return data.set(k,v)
get(k): return data.has(k) ? data.get(k) : (outer ? outer.get(k) : null)
--- core module ---------------------------------
ns = {'=: equal?,
'throw: throw,
'nil?: nil?,
'true?: true?,
'false?: false?,
'symbol: symbol,
'symbol?: symbol?,
'keyword: keyword,
'keyword?: keyword?,
'pr-str: (a) -> a.map(|s| pr_str(e,true)).join(" ")),
'str: (a) -> a.map(|s| pr_str(e,false)).join("")),
'prn: (a) -> println(a.map(|s| pr_str(e,true)).join(" ")),
'println: (a) -> println(a.map(|s| pr_str(e,false)).join(" ")),
'read-string: read_str,
'slurp read-file,
'<: lt,
'<=: lte,
'>: gt,
'>=: gte,
'+: add,
'-: sub,
'*: mult,
'/: div,
'list: list,
'list?: list?,
'vector: vector,
'vector?: vector?,
'hash-map: hash_map,
'map?: hash_map?,
'assoc: assoc,
'dissoc: dissoc,
'get: get,
'contains?: contains?,
'keys: keys,
'vals: vals,
'sequential? sequential?,
'cons: (a) -> concat([a[0]], a[1]),
'concat: (a) -> reduce(concat, [], a),
'vec: (l) -> l converted to vector,
'nth: (a) -> a[0][a[1]] OR raise "nth: index out of range",
'first: (a) -> a[0][0] OR nil,
'rest: (a) -> a[0][1..] OR list(),
'empty?: empty?,
'count: count,
'apply: apply,
'map: map,
'atom: (a) -> new Atom(a[0]),
'atom?: (a) -> type(a[0]) == "atom",
'deref: (a) -> a[0].val,
'reset!: (a) -> a[0].val = a[1],
'swap!: swap!}