madlisp/src/Printer.php

68 lines
2.2 KiB
PHP
Raw Normal View History

2020-05-28 10:10:00 +00:00
<?php
2020-12-14 01:49:07 +00:00
/**
* MadLisp language
* @link http://madlisp.com/
* @copyright Copyright (c) 2020 Pekka Laiho
*/
2020-05-28 10:10:00 +00:00
namespace MadLisp;
class Printer
{
2020-12-08 11:01:44 +00:00
public function print($ast, bool $readable): void
2020-05-28 10:10:00 +00:00
{
2020-12-08 10:39:26 +00:00
print($this->pstr($ast, $readable));
}
2020-12-08 11:01:44 +00:00
public function pstr($ast, bool $readable): string
2020-12-08 10:39:26 +00:00
{
return $this->doPrint($ast, $readable);
2020-05-28 10:10:00 +00:00
}
private function doPrint($a, bool $readable): string
2020-05-28 10:10:00 +00:00
{
if ($a instanceof Func) {
2020-12-06 01:26:27 +00:00
if ($a->isMacro()) {
return '<macro>';
} else {
return '<function>';
}
2020-05-28 10:10:00 +00:00
} elseif ($a instanceof MList) {
return '(' . implode(' ', array_map(fn ($b) => $this->doPrint($b, $readable), $a->getData())) . ')';
2020-05-31 04:34:24 +00:00
} elseif ($a instanceof Vector) {
return '[' . implode(' ', array_map(fn ($b) => $this->doPrint($b, $readable), $a->getData())) . ']';
2020-05-28 10:10:00 +00:00
} elseif ($a instanceof Hash) {
return '{' . implode(' ', array_map(fn ($key, $val) => $this->doPrint($key, $readable) . ':' . $this->doPrint($val, $readable),
2020-05-31 04:34:24 +00:00
array_keys($a->getData()), array_values($a->getData()))) . '}';
2020-05-28 10:10:00 +00:00
} elseif ($a instanceof Symbol) {
2020-05-31 04:34:24 +00:00
return $a->getName();
2020-06-19 06:46:52 +00:00
} elseif (is_object($a)) {
$class = get_class($a);
return "<object<$class>>";
} elseif (is_resource($a)) {
return '<resource>';
2020-05-28 10:10:00 +00:00
} elseif ($a === true) {
2020-05-31 04:34:24 +00:00
return 'true';
2020-05-28 10:10:00 +00:00
} elseif ($a === false) {
2020-05-31 04:34:24 +00:00
return 'false';
2020-05-28 10:10:00 +00:00
} elseif ($a === null) {
2020-06-02 02:51:21 +00:00
return 'null';
2020-05-28 10:10:00 +00:00
} elseif (is_string($a)) {
if ($readable) {
$a = str_replace("\\", "\\\\", $a);
$a = str_replace("\n", "\\n", $a);
$a = str_replace("\r", "\\r", $a);
2020-12-16 02:12:40 +00:00
$a = str_replace("\t", "\\t", $a);
$a = str_replace("\v", "\\v", $a);
$a = str_replace("\0", "\\0", $a);
$a = str_replace("\"", "\\\"", $a);
return '"' . $a . '"';
} else {
return $a;
}
2020-05-28 10:10:00 +00:00
} else {
2020-05-31 04:34:24 +00:00
return $a;
2020-05-28 10:10:00 +00:00
}
}
}