blib/lib/Seis/CLI.pm untested

filter: Statementstmt 0.0% 0 / 83 Branchbran 0.0% 0 / 18 Conditioncond 0.0% 0 / 3 MC/DCmcdc 0.0% 0 / 2 Subroutinesub 0.0% 0 / 16 Podpod 0.0% 0 / 5 totaltotal 0.0% 0 / 127 CC 10 SCAR 21.4
CC
10
Cov
0%
compile
20.0
run
12.0
run_repl
12.0
CRAP 8.5
1 package Seis::CLI;
2 use strict;
3 use warnings;
4 use utf8;
5 use 5.010_001;
6  
7 use Seis;
8 use Getopt::Long;
9 use Data::Dumper;
10 use Perl6::PVIP;
11  
12 use Class::XSAccessor
13 accessors => {
14 map { $_ => $_ } qw(
15 dump_ast
16 dump_ast_json
17 dump_compiled
18 compile_only
19 )
20 }
21 ;
22  
23 sub new {
24 my $class = shift;
25 bless {}, $class;
26 }
27  
28 sub run {
29 my $self = shift;
30  
31 my $p = Getopt::Long::Parser->new(
32 config => [qw(posix_default no_ignore_case auto_help)]
33 );
34 $p->getoptions(
35 'e=s' => \my $eval,
36 'debug' => \$self->{dump_compiled},
37 'ast' => \$self->{dump_ast},
38 'ast-json' => \$self->{dump_ast_json},
39 'c' => \$self->{compile_only},
40 );
41  
42 if (defined $eval) {
43 $self->compile_and_run($eval, '-e');
44 } elsif (@ARGV) {
45 my $fname= shift @ARGV;
46 open my $fh, '<', $fname
47 or Carp::croak("Can't open '$fname' for reading: '$!'");
48 my $src = scalar(do { local $/; <$fh> });
49 $self->compile_and_run($src, $fname);
50 } else {
51 $self->run_repl();
52 }
53 }
54  
55 sub run_repl {
56 my $self = shift;
57  
58 require Caroline;
59  
60 my $caroline = Caroline->new();
61 while (defined(my $line = $caroline->readline('seis> '))) {
62 if ($line =~ /\S/) {
63 $caroline->history_add($line);
64 my $compiled = $self->compile($line, '<repl>');
65 my $ret = eval $compiled;
66 if ($@) {
67 print STDERR $@ . "\n";
68 } else {
69 warn Dumper($ret);
70 }
71 }
72 }
73 }
74  
75 sub compile_and_run {
76 my ($self, $code, $filename) = @_;
77 my $compiled = $self->compile($code, $filename);
78 return if $self->{compile_only};
79 my $ret = eval $compiled;
80 die $@ if $@;
81 $ret;
82 }
83  
84 sub compile {
85 my ($self, $code, $filename) = @_;
86  
87 my $compiler = Seis::Compiler->new();
88 my $compiled = $compiler->compile($code, $filename);
89 if ($self->dump_ast) {
90 print "*** AST ***\n";
91 print Perl6::PVIP->new->parse_string($code)->as_sexp;
92 print "\n*** /AST ***\n";
93 print "\n\n";
94 }
95 if ($self->dump_ast_json) {
96 require JSON::PP;
97 print "*** AST ***\n";
98 print JSON::PP->new->pretty(1)->encode(Perl6::PVIP->new->parse_string($code)->perl);
99 print "\n*** /AST ***\n";
100 print "\n\n";
101 }
102 if ($self->dump_compiled) {
103 print "------ Compiled code:\n$compiled\n---------------\n";
104 }
105 return $compiled;
106 }
107  
108 1;
109