diff --git a/lib/Minilisp.pm b/lib/Minilisp.pm index de2c8ab..d871913 100644 --- a/lib/Minilisp.pm +++ b/lib/Minilisp.pm @@ -405,15 +405,25 @@ sub parser { } } +sub parser_many_expr { + my $ts = shift; + my @exprs; + + while (scalar(@$ts) && !peek_token($ts,RPAREN)) + { + push @exprs, parser_expr($ts); + } + + return @exprs; +} + sub parser_prog { my $ts = shift; - my @steps; + my @steps = parser_many_expr($ts); - while (scalar @$ts) - { - push @steps, parser_expr($ts); - } + die "Unexpected token " . $ts->[0]->{type} . " after end of program" + if scalar(@$ts); return sub { my $ctx = shift; @@ -480,11 +490,7 @@ sub parser_list { slurp_token($ts, LPAREN, "Expected ( after ' for list"); - my @elements; - while (!peek_token($ts,RPAREN)) - { - push @elements, parser_expr($ts); - } + my @elements = parser_many_expr($ts); slurp_token($ts, RPAREN, "Expected ) after list"); @@ -514,12 +520,7 @@ sub parser_call { my $fn = parser_expr($ts); - my @params; - - while (!peek_token($ts,RPAREN)) - { - push @params, parser_expr($ts); - } + my @params = parser_many_expr($ts); slurp_token($ts, RPAREN, "Expecte ) after call"); @@ -643,12 +644,7 @@ $macros{if} = \¯o_if; sub macro_progn { my $ts = shift; - my @steps; - - while (!peek_token($ts,RPAREN)) - { - push @steps, parser_expr($ts); - } + my @steps = parser_many_expr($ts); return sub { my $ctx = shift; @@ -782,11 +778,7 @@ $macros{set} = \¯o_set; sub macro_and { my $ts = shift; - my @operands_parsed; - while (!peek_token($ts,RPAREN)) - { - push @operands_parsed, parser_expr($ts); - } + my @operands_parsed = parser_many_expr($ts); return sub { my $ctx = shift; @@ -806,11 +798,7 @@ $macros{and} = \¯o_and; sub macro_or { my $ts = shift; - my @operands_parsed; - while (!peek_token($ts,RPAREN)) - { - push @operands_parsed, parser_expr($ts); - } + my @operands_parsed = parser_many_expr($ts); return sub { my $ctx = shift;