diff --git a/README.md b/README.md index e1ee750..509583c 100644 --- a/README.md +++ b/README.md @@ -18,7 +18,7 @@ The core project does not have any dependencies to external [Composer](https://g ## Usage -Use the **run.php** file to invoke the interpreter. You can start the Repl with the -r switch: +Use the **run.php** file to invoke the interpreter from the command line. You can start the Repl with the -r switch: ``` $ php run.php -r @@ -44,6 +44,14 @@ $ echo "(+ 1 2 3)" | php run.php 6 ``` +## Init file + +You can create an init file in your home directory with the name `.madlisp_init`. This file is automatically executed when the interpreter is started. It is useful for registering commonly used functions and performing other initialization. + +## Using from PHP + +You can use the [LispFactory](src/LispFactory.php) class to create an instance of the interpreter if you wish to embed the MadLisp language in your PHP application and call it directly from your code. + ## Types ### Numbers diff --git a/run.php b/run.php index 0e2d7b1..cf8ce4d 100644 --- a/run.php +++ b/run.php @@ -8,7 +8,7 @@ if (php_sapi_name() != 'cli') { function ml_repl($lisp) { // Read history - $historyFile = $_SERVER['HOME'] . '/.madlisp_history'; + $historyFile = $_SERVER['HOME'] . DIRECTORY_SEPARATOR . '.madlisp_history'; if (is_readable($historyFile)) { readline_read_history($historyFile); } @@ -37,6 +37,12 @@ function ml_repl($lisp) $factory = new MadLisp\LispFactory(); $lisp = $factory->make(); +// Load the user's init file if present +$initfile = $_SERVER['HOME'] . DIRECTORY_SEPARATOR . '.madlisp_init'; +if (is_readable($initfile)) { + $lisp->readEval("(load \"$initfile\")"); +} + if ($argc < 2) { // Read input from stdin $input = file_get_contents('php://stdin'); diff --git a/src/Lisp.php b/src/Lisp.php index 2e3d559..1263d99 100644 --- a/src/Lisp.php +++ b/src/Lisp.php @@ -18,13 +18,19 @@ class Lisp $this->env = $env; } - public function rep(string $input, bool $printReadable): void + public function readEval(string $input) { $tokens = $this->tokenizer->tokenize($input); $expr = $this->reader->read($tokens); - $result = $this->eval->eval($expr, $this->env); + return $this->eval->eval($expr, $this->env); + } + + // read, eval, print + public function rep(string $input, bool $printReadable): void + { + $result = $this->readEval($input); $this->printer->print($result, $printReadable); }