From 9e4dffef2b7895d8e346294eaef1b38dcdfeec91 Mon Sep 17 00:00:00 2001 From: Pekka Laiho Date: Mon, 1 Jun 2020 20:19:26 +0700 Subject: [PATCH] support for (doc) --- src/CoreFunc.php | 5 ++--- src/Func.php | 9 ++++++++- src/Lisp.php | 10 ++++++++++ 3 files changed, 20 insertions(+), 4 deletions(-) diff --git a/src/CoreFunc.php b/src/CoreFunc.php index 9a98538..d5f2acc 100644 --- a/src/CoreFunc.php +++ b/src/CoreFunc.php @@ -6,17 +6,16 @@ use Closure; class CoreFunc extends Func { protected string $name; - protected string $doc; protected int $minArgs; protected int $maxArgs; public function __construct(string $name, string $doc, int $minArgs, int $maxArgs, Closure $closure) { + parent::__construct($closure, $doc); + $this->name = $name; - $this->doc = $doc; $this->minArgs = $minArgs; $this->maxArgs = $maxArgs; - $this->closure = $closure; } public function call(array $args) diff --git a/src/Func.php b/src/Func.php index 1f88580..21662ea 100644 --- a/src/Func.php +++ b/src/Func.php @@ -6,10 +6,12 @@ use Closure; abstract class Func { protected Closure $closure; + protected ?string $doc; - public function __construct(Closure $closure) + public function __construct(Closure $closure, ?string $doc = null) { $this->closure = $closure; + $this->doc = $doc; } public function getClosure(): Closure @@ -17,6 +19,11 @@ abstract class Func return $this->closure; } + public function getDoc(): ?string + { + return $this->doc; + } + public function call(array $args) { return ($this->closure)(...$args); diff --git a/src/Lisp.php b/src/Lisp.php index 9fdb9fc..05cde8d 100644 --- a/src/Lisp.php +++ b/src/Lisp.php @@ -29,6 +29,16 @@ class Lisp public function register(Env $env): void { + $env->set('doc', new CoreFunc('doc', 'Get documentation for a function.', 1, 1, + function ($a) { + if ($a instanceof Func) { + return $a->getDoc(); + } + + throw new MadLispException('first argument to doc is not function'); + } + )); + $env->set('eval', new CoreFunc('eval', 'Evaluate arguments.', 1, -1, function (...$args) use ($env) { $results = $this->eval->eval($args, $env);