-
Notifications
You must be signed in to change notification settings - Fork 0
/
Read.pm
112 lines (92 loc) · 2.1 KB
/
Read.pm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
package Read;
use strict;
use warnings;
use base 'Exporter';
use vars qw/ @EXPORT_OK /;
use Cell;
use Functions qw/ nil cons /;
use IO::Scalar;
BEGIN {
@EXPORT_OK = qw/
read_string
read_stream
/;
}
sub read_string
{
my $string = shift;
my @symbols = split(//, $string);
return read_stream(\@symbols);
}
sub read_stream
{
my $stream = shift;
while (defined(my $char = shift @$stream)) {
if ($char =~ /\d/) {
return read_number($char, $stream)
} elsif ($char eq '"') {
return read_string_literal($stream);
} elsif ($char =~ /[a-zA-Z]/) {
return read_symbol($char, $stream);
} elsif ($char eq '(') {
return read_list($char, $stream);
} elsif ($char =~ /\s/) {
next;
}
}
die "Encounted unexpected end of stream";
}
sub read_number
{
my ($number, $stream) = @_;
while (my $char = shift @$stream) {
if ($char =~ /[0-9.]/) {
$number .= $char;
} elsif ($char =~ /\s/) {
return $number;
} else {
die "Encountered a non-number character in stream";
}
}
return $number;
}
sub read_symbol
{
my ($symbol, $stream) = @_;
while (my $char = shift @$stream) {
if ($char =~ /[a-zA-Z0-9_:-]/) {
$symbol .= $char;
} elsif ($char =~ /\s/) {
return $symbol;
} elsif ($char eq ')') {
unshift @$stream, $char;
return $symbol;
} else {
die "Encountered a non-symbol character in stream: '$char'";
}
}
return $symbol;
}
sub read_string_literal
{
my $stream = shift;
my $string = "";
while (defined(my $char = shift @$stream)) {
if ($char ne '"') {
$string .= $char;
} else {
return $string;
}
}
die "Encountered unexpected end of stream";
}
sub read_list
{
my ($start, $stream) = @_;
my $list = nil;
do {
$list = cons(read_stream($stream), $list);
} while ($stream->[0] ne ")");
return $list;
}
1;