2020-05-28 10:10:00 +00:00
|
|
|
<?php
|
|
|
|
namespace MadLisp;
|
|
|
|
|
|
|
|
class Printer
|
|
|
|
{
|
2020-06-16 13:38:46 +00:00
|
|
|
public function print($ast, bool $readable = true): void
|
2020-05-28 10:10:00 +00:00
|
|
|
{
|
2020-06-16 13:38:46 +00:00
|
|
|
print($this->doPrint($ast, $readable));
|
2020-05-28 10:10:00 +00:00
|
|
|
}
|
|
|
|
|
2020-06-16 13:38:46 +00:00
|
|
|
private function doPrint($a, bool $readable): string
|
2020-05-28 10:10:00 +00:00
|
|
|
{
|
2020-05-31 10:50:29 +00:00
|
|
|
if ($a instanceof Func) {
|
2020-05-31 04:34:24 +00:00
|
|
|
return '<function>';
|
2020-05-28 10:10:00 +00:00
|
|
|
} elseif ($a instanceof MList) {
|
2020-06-16 13:38:46 +00:00
|
|
|
return '(' . implode(' ', array_map(fn ($b) => $this->doPrint($b, $readable), $a->getData())) . ')';
|
2020-05-31 04:34:24 +00:00
|
|
|
} elseif ($a instanceof Vector) {
|
2020-06-16 13:38:46 +00:00
|
|
|
return '[' . implode(' ', array_map(fn ($b) => $this->doPrint($b, $readable), $a->getData())) . ']';
|
2020-05-28 10:10:00 +00:00
|
|
|
} elseif ($a instanceof Hash) {
|
2020-06-16 13:38:46 +00:00
|
|
|
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)) {
|
2020-06-16 13:38:46 +00:00
|
|
|
if ($readable) {
|
|
|
|
$a = str_replace("\\", "\\\\", $a);
|
|
|
|
$a = str_replace("\n", "\\n", $a);
|
|
|
|
$a = str_replace("\r", "\\r", $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
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|