error function, loadf function

This commit is contained in:
Pekka Laiho 2020-06-06 09:39:12 +07:00
parent 24ba1caf02
commit fae099d659
3 changed files with 18 additions and 4 deletions

View File

@ -25,5 +25,8 @@ function ml_get_lisp(): array
(new MadLisp\Lib\Time())->register($env); (new MadLisp\Lib\Time())->register($env);
(new MadLisp\Lib\Types())->register($env); (new MadLisp\Lib\Types())->register($env);
// Functions defined in lisp itself
$lisp->re('(def loadf (fn (f) (if (file? f) (eval (read (str "(do " (fread f) ")"))) (error (str "file " f " does not exist")))))', $env);
return [$lisp, $env]; return [$lisp, $env];
} }

View File

@ -62,8 +62,8 @@ class Evaller
$value = $this->eval($ast->get(2), $env); $value = $this->eval($ast->get(2), $env);
return $env->set($ast->get(1)->getName(), $value); return $env->set($ast->get(1)->getName(), $value);
} elseif ($ast->get(0)->getName() == 'do') { } elseif ($ast->get(0)->getName() == 'do') {
if ($ast->count() < 2) { if ($ast->count() == 1) {
throw new MadLispException("do requires at least 1 argument"); return null;
} }
for ($i = 1; $i < $ast->count() - 1; $i++) { for ($i = 1; $i < $ast->count() - 1; $i++) {

View File

@ -16,13 +16,18 @@ class Lisp
$this->printer = $printer; $this->printer = $printer;
} }
public function rep(string $input, Env $env): void public function re(string $input, Env $env)
{ {
$tokens = $this->tokenizer->tokenize($input); $tokens = $this->tokenizer->tokenize($input);
$expr = $this->reader->read($tokens); $expr = $this->reader->read($tokens);
$result = $this->eval->eval($expr, $env); return $this->eval->eval($expr, $env);
}
public function rep(string $input, Env $env): void
{
$result = $this->re($input, $env);
$this->printer->print($result); $this->printer->print($result);
} }
@ -53,5 +58,11 @@ class Lisp
return null; return null;
} }
)); ));
$env->set('error', new CoreFunc('error', 'Throw an exception using argument (string) as message.', 1, 1,
function (string $error) {
throw new MadLispException($error);
}
));
} }
} }