summaryrefslogtreecommitdiffstats
path: root/lib/Reply/Plugin/Defaults.pm
blob: adf5c0ea43759db9f949d91944ca0a0789499c9b (plain) (blame)
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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
package Reply::Plugin::Defaults;

# XXX Eval::Closure imposes its own hints on things that are eval'ed at the
# moment, but this may be fixed in the future
BEGIN {
    our $default_hints = $^H;
    our $default_hinthash = { %^H };
    our $default_warning_bits = ${^WARNING_BITS};
}

use strict;
use warnings;

use base 'Reply::Plugin';

use Devel::LexAlias 'lexalias';
use Eval::Closure;

sub new {
    my $class = shift;

    my $self = $class->SUPER::new(@_);
    $self->{quit} = 0;
    $self->{env} = [];
    $self->{package} = 'main';

    return $self;
}

sub prompt { "> " }

sub read_line {
    my $self = shift;
    my ($next, $prompt) = @_;

    print $prompt;
    return scalar <>;
}

(my $PREFIX = <<'PREFIX') =~ s/__PACKAGE__/__PACKAGE__/ge;
BEGIN {
    $^H = $__PACKAGE__::default_hints;
    %^H = %$__PACKAGE__::default_hinthash;
    ${^WARNING_BITS} = $__PACKAGE__::default_warning_bits;
}
PREFIX

sub compile {
    my $self = shift;
    my ($next, $line, %args) = @_;

    my $env = { map { %$_ } @{ $self->{env} } };

    my $prefix = "package $self->{package};\n$PREFIX";

    my $code = eval_closure(
        source      => "sub {\n$prefix;\n$line\n}",
        terse_error => 1,
        environment => $env,
        %args,
    );

    for my $name (keys %$env) {
        lexalias($code, $name, $env->{$name});
    }

    return $code;
}

sub lexical_environment {
    my $self = shift;
    my ($env) = @_;
    push @{ $self->{env} }, $env;
}

sub package {
    my $self = shift;
    my ($package) = @_;
    $self->{package} = $package;
}

sub execute {
    my $self = shift;
    my ($next, $code, @args) = @_;

    return $code->(@args);
}

sub print_error {
    my $self = shift;
    my ($next, $error) = @_;

    print $error
        if defined $error;
}

sub print_result {
    my $self = shift;
    my ($next, @result) = @_;

    print @result, "\n"
        if @result;
}

sub command_q {
    my $self = shift;
    $self->{quit} = 1;
    return '';
}

sub loop {
    my $self = shift;
    my ($continue) = @_;

    $continue = 0 if $self->{quit};

    return $continue;
}

=begin Pod::Coverage

  new
  command_q

=end Pod::Coverage

=cut

1;