1
1
mirror of https://github.com/kanaka/mal.git synced 2024-09-20 18:18:51 +03:00
mal/impls/ts/step7_quote.ts
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

241 lines
8.1 KiB
TypeScript

import { readline } from "./node_readline";
import { Node, MalType, MalString, MalNil, MalList, MalVector, MalHashMap, MalSymbol, MalFunction, isAST, isSeq } from "./types";
import { Env } from "./env";
import * as core from "./core";
import { readStr } from "./reader";
import { prStr } from "./printer";
// READ
function read(str: string): MalType {
return readStr(str);
}
function starts_with(lst: MalType[], sym: string): boolean {
if (lst.length == 2) {
let a0 = lst[0]
switch (a0.type) {
case Node.Symbol:
return a0.v === sym;
}
}
return false;
}
function qq_loop(elt: MalType, acc: MalList): MalList {
if (elt.type == Node.List && starts_with(elt.list, "splice-unquote")) {
return new MalList([MalSymbol.get("concat"), elt.list[1], acc]);
} else {
return new MalList([MalSymbol.get("cons"), quasiquote(elt), acc]);
}
}
function qq_foldr(xs : MalType[]): MalList {
let acc = new MalList([])
for (let i=xs.length-1; 0<=i; i-=1) {
acc = qq_loop(xs[i], acc)
}
return acc;
}
function quasiquote(ast: MalType): MalType {
switch (ast.type) {
case Node.Symbol:
return new MalList([MalSymbol.get("quote"), ast]);
case Node.HashMap:
return new MalList([MalSymbol.get("quote"), ast]);
case Node.List:
if (starts_with(ast.list, "unquote")) {
return ast.list[1];
} else {
return qq_foldr(ast.list);
}
case Node.Vector:
return new MalList([MalSymbol.get("vec"), qq_foldr(ast.list)]);
default:
return ast;
}
}
// EVAL
function evalMal(ast: MalType, env: Env): MalType {
loop: while (true) {
// Output a debug line if the option is enabled.
const dbgeval : MalType | null = env.get("DEBUG-EVAL");
if (dbgeval !== null
&& dbgeval.type !== Node.Nil
&& (dbgeval.type !== Node.Boolean || dbgeval.v))
console.log("EVAL:", prStr(ast));
// Deal with non-list types.
switch (ast.type) {
case Node.Symbol:
const f : MalType | null = env.get(ast.v);
if (!f) {
throw new Error(`'${ast.v}' not found`);
}
return f;
case Node.List:
break;
case Node.Vector:
return new MalVector(ast.list.map(ast => evalMal(ast, env)));
case Node.HashMap:
const list: MalType[] = [];
for (const [key, value] of ast.entries()) {
list.push(key);
list.push(evalMal(value, env));
}
return new MalHashMap(list);
default:
return ast;
}
if (ast.list.length === 0) {
return ast;
}
const first = ast.list[0];
switch (first.type) {
case Node.Symbol:
switch (first.v) {
case "def!": {
const [, key, value] = ast.list;
if (key.type !== Node.Symbol) {
throw new Error(`unexpected token type: ${key.type}, expected: symbol`);
}
if (!value) {
throw new Error(`unexpected syntax`);
}
return env.set(key.v, evalMal(value, env));
}
case "let*": {
env = new Env(env);
const pairs = ast.list[1];
if (!isSeq(pairs)) {
throw new Error(`unexpected token type: ${pairs.type}, expected: list or vector`);
}
for (let i = 0; i < pairs.list.length; i += 2) {
const key = pairs.list[i];
const value = pairs.list[i + 1];
if (key.type !== Node.Symbol) {
throw new Error(`unexpected token type: ${key.type}, expected: symbol`);
}
if (!key || !value) {
throw new Error(`unexpected syntax`);
}
env.set(key.v, evalMal(value, env));
}
ast = ast.list[2];
continue loop;
}
case "quote": {
return ast.list[1];
}
case "quasiquote": {
ast = quasiquote(ast.list[1]);
continue loop;
}
case "do": {
for (let i = 1; i < ast.list.length - 1; i++)
evalMal(ast.list[i], env);
ast = ast.list[ast.list.length - 1];
continue loop;
}
case "if": {
const [, cond, thenExpr, elseExrp] = ast.list;
const ret = evalMal(cond, env);
let b = true;
if (ret.type === Node.Boolean && !ret.v) {
b = false;
} else if (ret.type === Node.Nil) {
b = false;
}
if (b) {
ast = thenExpr;
} else if (elseExrp) {
ast = elseExrp;
} else {
ast = MalNil.instance;
}
continue loop;
}
case "fn*": {
const [, params, bodyAst] = ast.list;
if (!isSeq(params)) {
throw new Error(`unexpected return type: ${params.type}, expected: list or vector`);
}
const symbols = params.list.map(param => {
if (param.type !== Node.Symbol) {
throw new Error(`unexpected return type: ${param.type}, expected: symbol`);
}
return param;
});
return MalFunction.fromLisp(evalMal, env, symbols, bodyAst);
}
}
}
const f : MalType = evalMal(first, env);
if (f.type !== Node.Function) {
throw new Error(`unexpected token: ${f.type}, expected: function`);
}
const args : Array<MalType> = ast.list.slice(1).map(x => evalMal(x, env));
if (f.ast) {
ast = f.ast;
env = f.newEnv(args);
continue loop;
}
return f.func(...args);
}
}
// PRINT
function print(exp: MalType): string {
return prStr(exp);
}
const replEnv = new Env();
function rep(str: string): string {
return print(evalMal(read(str), replEnv));
}
// core.EXT: defined using Racket
core.ns.forEach((value, key) => {
replEnv.set(key, value);
});
replEnv.set("eval", MalFunction.fromBootstrap(ast => {
if (!ast) {
throw new Error(`undefined argument`);
}
return evalMal(ast, replEnv);
}));
replEnv.set("*ARGV*", new MalList([]));
// 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)")))))`);
if (typeof process !== "undefined" && 2 < process.argv.length) {
replEnv.set("*ARGV*", new MalList(process.argv.slice(3).map(s => new MalString(s))));
rep(`(load-file "${process.argv[2]}")`);
process.exit(0);
}
while (true) {
const line = readline("user> ");
if (line == null) {
break;
}
if (line === "") {
continue;
}
try {
console.log(rep(line));
} catch (e) {
if (isAST(e)) {
console.error("Error:", prStr(e));
} else {
const err: Error = e;
console.error("Error:", err.message);
}
}
}