support for init file

This commit is contained in:
Pekka Laiho 2020-10-24 14:27:02 +07:00
parent d4d3de911e
commit 330fda6715
3 changed files with 24 additions and 4 deletions

View File

@ -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

View File

@ -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');

View File

@ -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);
}