| 1 | use strict; use warnings; | ||
| 2 | package Lingy::Env; | ||
| 3 | |||
| 4 | use Lingy::Common; | ||
| 5 | |||
| 6 | sub new { | ||
| 7 | my ($class, %args) = @_; | ||
| 8 | my $self = bless { | ||
| 9 | outer => $args{outer}, | ||
| 10 | space => $args{space} // {}, | ||
| 11 | }, $class; | ||
| 12 | my $binds = [ @{$args{binds} // []} ]; | ||
| 13 | my $exprs = $args{exprs} // []; | ||
| 14 | while (@$binds) { | ||
| 15 | if ("$binds->[0]" eq '&') { | ||
| 16 | shift @$binds; | ||
| 17 | $exprs = [list([@$exprs])]; | ||
| 18 | } | ||
| 19 | $self->{space}{shift(@$binds)} = (shift(@$exprs) // nil); | ||
| 20 | } | ||
| 21 | if (my $outer = $self->{outer}) { | ||
| 22 | $self->{LOOP} = $outer->{LOOP} if $outer->{LOOP}; | ||
| 23 | $self->{RECUR} = $outer->{RECUR} if $outer->{RECUR}; | ||
| 24 | } | ||
| 25 | return $self; | ||
| 26 | } | ||
| 27 | |||
| 28 | sub set { | ||
| 29 | my ($self, $symbol, $value) = @_; | ||
| 30 | my $space = $self->{space}; | ||
| 31 | $space->{$symbol} = $value; | ||
| 32 | return ref($space) eq 'HASH' | ||
| 33 | ? $symbol | ||
| 34 | : symbol($space->_name . "/$symbol"); | ||
| 35 | } | ||
| 36 | |||
| 37 | sub get { | ||
| 38 | my ($self, $symbol, $optional) = @_; | ||
| 39 | |||
| 40 | # XXX Temporary hack until Vars | ||
| 41 | if ("$symbol" eq '*ns*') { | ||
| 42 | return RT->current_ns; | ||
| 43 | } | ||
| 44 | |||
| 45 | return $self->get_qualified($symbol, $optional) | ||
| 46 | if $symbol =~ m{./.}; | ||
| 47 | |||
| 48 | while ($self) { | ||
| 49 | my $space = $self->{space}; | ||
| 50 | if (defined(my $value = $space->{$symbol})) { | ||
| 51 | return $value; | ||
| 52 | } | ||
| 53 | $self = $self->{outer}; | ||
| 54 | } | ||
| 55 | |||
| 56 | if (my $class = RT->current_ns->{"$symbol"}) { | ||
| 57 | return $class; | ||
| 58 | } | ||
| 59 | |||
| 60 | return if $optional; | ||
| 61 | |||
| 62 | err "Class not found: '$symbol'" | ||
| 63 | if $symbol =~ /\w\.\w/; | ||
| 64 | |||
| 65 | err "Unable to resolve symbol: '$symbol' in this context"; | ||
| 66 | } | ||
| 67 | |||
| 68 | sub get_qualified { | ||
| 69 | my ($self, $symbol, $optional) = @_; | ||
| 70 | |||
| 71 | $symbol =~ m{^(.*)/(.*)$} or die; | ||
| 72 | my $space_name = $1; | ||
| 73 | my $symbol_name = $2; | ||
| 74 | |||
| 75 | if (my $ns = RT->core_ns) { | ||
| 76 | if (my $class = RT->core_ns->{$space_name}) { | ||
| 77 | return \&{"${class}::$symbol_name"}; | ||
| 78 | } | ||
| 79 | } | ||
| 80 | if (my $class = RT->current_ns->{$space_name}) { | ||
| 81 | return \&{"${class}::$symbol_name"}; | ||
| 82 | } | ||
| 83 | |||
| 84 | my $ns = RT->namespaces->{$space_name} | ||
| 85 | or err "No such namespace: '$space_name'"; | ||
| 86 | |||
| 87 | if (defined(my $value = $ns->{$symbol_name})) { | ||
| 88 | return $value; | ||
| 89 | } | ||
| 90 | |||
| 91 | return if $optional; | ||
| 92 | |||
| 93 | err "Unable to resolve symbol: '$symbol' in this context"; | ||
| 94 | } | ||
| 95 | |||
| 96 | 1; |