madlisp/src/Printer.php

50 lines
1.7 KiB
PHP
Raw Normal View History

2020-05-28 10:10:00 +00:00
<?php
namespace MadLisp;
class Printer
{
public function print($ast, bool $readable = true): void
2020-05-28 10:10:00 +00:00
{
print($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-05-31 04:34:24 +00:00
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);
$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
}
}
}