1
1
mirror of https://github.com/kanaka/mal.git synced 2024-10-27 22:58:00 +03:00
mal/impls/perl/printer.pm
Joel Martin 8a19f60386 Move implementations into impls/ dir
- Reorder README to have implementation list after "learning tool"
  bullet.

- This also moves tests/ and libs/ into impls. It would be preferrable
  to have these directories at the top level.  However, this causes
  difficulties with the wasm implementations which need pre-open
  directories and have trouble with paths starting with "../../". So
  in lieu of that, symlink those directories to the top-level.

- Move the run_argv_test.sh script into the tests directory for
  general hygiene.
2020-02-10 23:50:16 -06:00

47 lines
1.1 KiB
Perl

package printer;
use strict;
use warnings;
use Exporter 'import';
our @EXPORT_OK = qw( _pr_str );
use types qw(thaw_key $nil $true $false);
use Data::Dumper;
use List::Util qw(pairmap);
sub _pr_str {
my($obj, $print_readably) = @_;
my($_r) = $print_readably // 1;
if ($obj->isa('Mal::List')) {
return '(' . join(' ', map { _pr_str($_, $_r) } @$obj) . ')';
} elsif ($obj->isa('Mal::Vector')) {
return '[' . join(' ', map { _pr_str($_, $_r) } @$obj) . ']';
} elsif ($obj->isa('Mal::HashMap')) {
return '{' . join(' ', pairmap { _pr_str(thaw_key($a), $_r) =>
_pr_str($b, $_r) } %$obj) . '}';
} elsif ($obj->isa('Mal::Keyword')) {
return ":$$obj";
} elsif ($obj->isa('Mal::String')) {
if ($_r) {
my $str = $$obj;
$str =~ s/\\/\\\\/g;
$str =~ s/"/\\"/g;
$str =~ s/\n/\\n/g;
return qq'"$str"';
} else {
return $$obj;
}
} elsif ($obj->isa('Mal::Atom')) {
return '(atom ' . _pr_str($$obj) . ")";
} elsif ($obj->isa('Mal::Function')) {
return "<fn* $obj>";
} elsif ($obj->isa('Mal::Macro')) {
return "<macro* $obj>";
} else {
return $$obj;
}
}
1;