File Coverage

blib/lib/Eval/Context.pm
Criterion Covered Total %
statement 67 337 19.8
branch 7 148 4.7
condition 11 46 23.9
subroutine 16 42 38.1
pod 22 22 100.0
total 123 595 20.6


line stmt bran cond sub pod time code
1              
2             package Eval::Context ;
3              
4 1     1   30396 use strict;
  1         2  
  1         29  
5 1     1   5 use warnings ;
  1         2  
  1         26  
6              
7             BEGIN 
8             {
9 1     1   4 use vars qw ($VERSION);
  1         5  
  1         45  
10 1     1   15 $VERSION = '0.09' ;
11             }
12              
13             #-------------------------------------------------------------------------------
14              
15 1     1   852 use English qw( -no_match_vars ) ;
  1         4588  
  1         5  
16              
17 1     1   1229 use Readonly ;
  1         3730  
  1         160  
18             Readonly my $EMPTY_STRING => q{} ;
19              
20             Readonly our $SHARED => 0 ;
21             Readonly our $PERSISTENT => 1 ;
22              
23             my $flag ;
24             Readonly our $USE => bless \$flag, 'USE_PERSISTENT' ;
25              
26 1     1   11 use Carp qw(carp croak confess) ;
  1         3  
  1         80  
27 1     1   1135 use File::Slurp ;
  1         15442  
  1         88  
28 1     1   971 use Sub::Install qw(install_sub reinstall_sub) ;
  1         1596  
  1         8  
29 1     1   895 use Symbol qw(delete_package);
  1         821  
  1         53  
30 1     1   880 use Safe ;
  1         48850  
  1         77  
31 1     1   1401 use Data::Dumper ;
  1         10792  
  1         5958  
32              
33             #-------------------------------------------------------------------------------
34              
35             =head1 NAME
36            
37             Eval::Context - Evalute perl code in context wraper
38            
39             =head1 SYNOPSIS
40            
41             use Eval::Context ;
42            
43             my $context = new Eval::Context(PRE_CODE => "use strict;\nuse warnings;\n") ;
44            
45             # code will be evaluated with strict and warnings loaded in the context.
46            
47             $context->eval(CODE => 'print "evaluated in an Eval::Context!" ;') ;
48             $context->eval(CODE_FROM_FILE => 'file.pl') ;
49            
50             =head1 DESCRIPTION
51            
52             This module define a subroutine that let you evaluate Perl code in a specific context. The code can be passed directly as
53             a string or as a file name to read from. It also provides some subroutines to let you define and optionally share
54             variables and subroutines between your code and the code you wish to evaluate. Finally there is some support for running
55             your code in a safe compartment.
56            
57             =head1 Don't play with fire!
58            
59             Don't start using this module, or any other module, thinking it will let you take code from anywhere and be
60             safe. Read perlsec, Safe, Opcode, Taint and other security related documents. Control your input.
61            
62             =head1 SUBROUTINES/METHODS
63            
64             Subroutines that are not part of the public interface are marked with [p].
65            
66             =cut
67              
68             #-------------------------------------------------------------------------------
69              
70             Readonly my $NEW_ARGUMENTS =>
71             [qw(
72             NAME PACKAGE SAFE PERL_EVAL_CONTEXT
73             PRE_CODE POST_CODE REMOVE_PACKAGE_AFTER_EVAL
74             INSTALL_SUBS INSTALL_VARIABLES EVAL_SIDE_PERSISTENT_VARIABLES
75             INTERACTION FILE LINE DISPLAY_SOURCE_IN_CONTEXT
76             )] ;
77              
78             sub new
79             {
80              
81             =head2 new(@named_arguments)
82            
83             Create an Eval::Context object. The object is used as a repository of "default" values for your code evaluations.
84             The context can be used many times. The values can be temporarily overridden during the C<eval> call.
85            
86             my $context = new Eval::Context() ; # default context
87            
88             my $context = new Eval::Context
89             (
90             NAME => 'libraries evaluation context',
91             PACKAGE => 'libraries',
92             SAFE => {...} ;
93            
94             PRE_CODE => "use strict ;\n"
95             POST_CODE => sub{},
96             PERL_EVAL_CONTEXT => undef,
97            
98             INSTALL_SUBS => {...},
99             INSTALL_VARIABLES => [...],
100             EVAL_SIDE_PERSISTENT_VARIABLES => {...},
101            
102             INTERACTION => {...},
103             DISPLAY_SOURCE_IN_CONTEXT => 1, #useful when debuging
104             ) ;
105            
106             I<ARGUMENTS>
107            
108             =over 2
109            
110             =item * @named_arguments - setup data for the object
111            
112             All the arguments optional. The argument passed to C<new> can also be passed to C<eval>. All arguments are named.
113            
114             =over 4
115            
116             =item * NAME - use when displaying information about the object.
117            
118             Set automatically to 'Anonymous' if not set. The name will also be reported
119             by perl if an error occurs during your code evaluation.
120            
121             =item * PACKAGE - the package the code passed to C<eval> will evaluated be in.
122            
123             If not set, a unique package name is generated and used for every C<eval> call.
124            
125             =item * REMOVE_PACKAGE_AFTER_EVAL - When set the content of the package after evaluation will be erase
126            
127             The default behavior is to remove all data from after the call to C<eval>.
128            
129             =item * PRE_CODE - code prepended to the code passed to I<eval>
130            
131             =item * POST_CODE - code appended to the code passed to I<eval>
132            
133             =item * PERL_EVAL_CONTEXT - the context to eval code in (void, scalar, list).
134            
135             This option Works as L<perlfunc/wantarray>. It will override the context in which C<eval> is called.
136            
137             =item * INSTALL_SUBS - subs that will be available in the eval.
138            
139             A hash where the keys are a function names and the values a code references.
140            
141             =item * SAFE
142            
143             This argument must be a hash reference. if the hash is empty, a default safe compartment will be used.
144             Read L<Safe> documentation for more information.
145            
146             SAFE => {} # default safe environment
147            
148             You can have a finer control over the safe compartment B<Eval::Context> that will be used.
149            
150             my $compartment = new Safe('ABC') ;
151            
152             my $context = new Eval::Context
153             (
154             SAFE => # controlling the safe environment
155             {
156             PACKAGE => 'ABC',
157             PRE_CODE => "use my module ;\n" # code we consider safe
158             USE_STRICT => 0, # set to 1 by default
159             COMPARTMENT => $compartment , # use default if not passed
160             } ,
161             }
162            
163             $context->eval(CODE => .....) ;
164            
165             =over 4
166            
167             =item * COMPARTMENT - a Safe object, you create, that will be used by B<Eval::Context>
168            
169             =item * USE_STRICT - Controls if L<strict> is used in the Safe compartment
170            
171             The default is to use strict. Note that L<perldoc/Safe> default is to NOT use strict (undocumented).
172            
173             =item * PRE_CODE - safe code you want to evaluate in the same context as the unsafe code
174            
175             This let you, for example, use certain modules which provide subroutines to be used
176             in the evaluated code. The default compartment is quite restrictive and you can't even use
177             L<strict> in it without tuning the safe compartment.
178            
179             =back
180            
181             A few remarks:
182            
183             - See L<http://rt.cpan.org/Ticket/Display.html?id=31090> on RT
184            
185             - Pass the same package name to your safe compartment and to B<Eval::Context>.
186            
187             - If you really want to be on the safe side, control your input. When you use a module, are you
188             sure the module hasn't been fiddle with?
189            
190             - Leave strict on. Even for trivial code.
191            
192             =item * INSTALL_VARIABLES - "Give me sugar baby" Ash.
193            
194             B<Eval::Context> has mechanisms you can use to set and share variables with the
195             code you will evaluate. There are two sides in an B<Eval::Context>. The I<caller-side>,
196             the side where the calls to C<eval> are made and the I<eval-side>, the side where the code to
197             be evaluated is run.
198            
199             =over 4
200            
201             =item * How should you get values back from the eval-side
202            
203             Although you can use the mechanisms below to get values from the I<eval-side>, the cleanest
204             way is to get the results directly from the C<eval> call.
205            
206             my $context = new Eval::Context() ;
207            
208             my ($scalr_new_value, $a_string) =
209             $context->eval
210             (
211             INSTALL_VARIABLES =>[[ '$scalar' => 42]] ,
212             CODE => "\$scalar++ ;\n (\$scalar, 'a string') ;",
213             ) ;
214            
215             =item * initializing variables on the I<eval side>
216            
217             You can pass B<INSTALL_VARIABLES> to C<new> or C<eval>. You can initialize different variables
218             for each run of C<eval>.
219            
220             my $context = new Eval::Context
221             (
222             INSTALL_VARIABLES =>
223             [
224             # variables on eval-side #initialization source
225             [ '$data' => 42],
226             [ '$scalar' => $scalar_caller_side ],
227             [ '%hash' => \%hash_caller_side ]
228             [ '$hash' => \%hash_caller_side ],
229             [ '$object' => $object ],
230             ] ,
231             ) ;
232            
233             The variables will be B<my> variables on the eval-side.
234            
235             You can declare variables of any of the base types supported by perl. The initialization
236             data , on the caller-side, is serialized and deserialized to make the values available
237             on the eval-side. Modifying the variables on the eval-side does not modify the variables
238             on the caller-side. The initialization data can be scalars or references and even B<my>
239             variables.
240            
241             =item * Persistent variables
242            
243             When evaluating code many times in the same context, you may wish to have variables persist
244             between evaluations. B<Eval::Context> allows you to declare, define and control such
245             I<state> variables.
246            
247             This mechanism lets you control which variables are persistent. Access to the persistent
248             variables is controlled per C<eval> run. Persistent variables are B<my> variables on
249             the I<eval-side>. Modifying the variables on the eval-side does not modify the variables
250             on the I<caller-side>.
251            
252             Define persistent variables:
253            
254             # note: creating persistent variables in 'new' makes little sense as
255             # it will force those values in the persistent variables for every run.
256             # This may or may not be what you want.
257            
258             my $context = new Eval::Context() ;
259            
260             $context->eval
261             (
262             INSTALL_VARIABLES =>
263             [
264             [ '$scalar' => 42 => $Eval::Context::PERSISTENT ] ,
265            
266             # make %hash and $hash available on the eval-side. both are
267             # initialized from the same caller-side hash
268             [ '%hash' => \%hash_caller_side => $Eval::Context::PERSISTENT ] ,
269             [ '$hash' => \%hash_caller_side => $Eval::Context::PERSISTENT ] ,
270             ],
271             CODE => '$scalar++',
272             ) ;
273            
274             Later, use the persistent value:
275            
276             $context->eval
277             (
278             INSTALL_VARIABLES =>
279             [
280             [ '$scalar' => $Eval::Context::USE => $Eval::Context::PERSISTENT ] ,
281             # here you decided %hash and $hash shouldn't be available on the eval-side
282             ],
283            
284             CODE => '$scalar',
285             ) ;
286            
287             B<$Eval::Context::USE> means I<"make the persistent variable and it's value available on the eval-side">.
288             Any other value will reinitialize the persistent variable. See also B<REMOVE_PERSISTENT> in C<eval>.
289            
290             =item * Manually synchronizing caller-side data with persistent eval-side data
291            
292             Although the first intent of persistent variables is to be used as state variables on
293             the eval-side, you can get persistent variables values on the caller-side. To change the
294             value of an I<eval-side> persistent variable, simply reinitialize it with B<INSTALL_VARIABLES>
295             next time you call C<eval>.
296            
297             my $context = new Eval::Context
298             (
299             INSTALL_VARIABLES =>
300             [
301             ['%hash' => \%hash_caller_side => $Eval::Context::PERSISTENT]
302             ] ,
303             ) ;
304            
305             $context->Eval(CODE => '$hash{A}++ ;') ;
306            
307             # throws exception if you request a non existing variable
308             my %hash_after_eval = $context->GetPersistantVariables('%hash') ;
309            
310            
311             =item * Getting the list of all the PERSISTENT variables
312            
313             my @persistent_variable_names = $context->GetPersistantVariablesNames() ;
314            
315             =item * Creating persistent variables on the eval-side
316            
317             The mechanism above gave you fine control over persistent variables on the I<eval-side>.
318             The negative side is that B<only> the variables you made persistent exist on the I<eval-side>.
319             B<Eval::Context> has another mechanism that allows the I<eval-side> to store variables
320             between evaluations without the I<caller-side> declaration of the variables.
321            
322             To allow the I<eval-side> to store any variable, add this to you C<new> call.
323            
324             my $context = new Eval::Context
325             (
326             PACKAGE => 'my_package',
327            
328             EVAL_SIDE_PERSISTENT_VARIABLES =>
329             {
330             SAVE => { NAME => 'SavePersistent', VALIDATOR => sub{} },
331             GET => { NAME => 'GetPersistent', VALIDATOR => sub{} },
332             },
333             ) ;
334            
335             The I<eval-side> can now store variables between calls to C<eval>
336            
337             SavePersistent('name', $value) ;
338            
339             later in another call to C<eval>:
340            
341             my $variable = GetPersistent('name') ;
342            
343             By fine tuning B<EVAL_SIDE_PERSISTENT_VARIABLES> you can control what variables are stored
344             by the I<eval-side>. This should seldom be used and only to help those storing data from
345             the I<eval-side>.
346            
347             You may have notices in the code above that a package name was passed as argument to C<new>. This
348             is very important as the package names that are automatically generated differ for each
349             C<eval> call. If you want to run all you I<eval-side> code in different packages (B<Eval::Context>
350             default behavior), you must tell B<Eval::Context> where to store the I<eval-side> values. This is
351             done by setting B<CATEGORY>
352            
353             The validator sub can verify if the value to be stored are valid, E.G.: variable name, variable
354             value is within range, ...
355            
356             Here is an example of code run in different packages but can share variables. Only variables
357             which names start with I<A> are valid.
358            
359             new Eval::Context
360             (
361             EVAL_SIDE_PERSISTENT_VARIABLES =>
362             {
363             CATEGORY => 'TEST',
364             SAVE =>
365             {
366             NAME => 'SavePersistent',
367             VALIDATOR => sub
368             {
369             my ($self, $name, $value, $package) = @_ ;
370             $self->{INTERACTION}{DIE}->
371             (
372             $self,
373             "SavePersistent: name '$name' doesn't start with A!"
374             ) unless $name =~ /^A/ ;
375             },
376             },
377            
378             GET => {NAME => 'GetPersistent',VALIDATOR => sub {}},
379             },
380             ) ;
381            
382             $context->eval(CODE => 'SavePersistent('A_variable', 123) ;') ;
383            
384             later:
385            
386             $context->eval(CODE => 'GetPersistent('A_variable') ;') ;
387            
388             =item * Shared variables
389            
390             You can also share references between the I<caller-side> and the I<eval-side>.
391            
392             my $context =
393             new Eval::Context
394             (
395             INSTALL_VARIABLES =>
396             [
397             # reference to reference only
398             [ '$scalar' => \$scalar => $Eval::Context::SHARED ],
399             [ '$hash' => \%hash_caller_side => $Eval::Context::SHARED ],
400             [ '$object' => $object => $Eval::Context::SHARED ],
401             ] ,
402             ) ;
403            
404             Modification of the variables on the I<eval-side> will modify the variable on the I<caller-side>.
405             There are but a few reasons to share references. Note that you can share references to B<my> variables.
406            
407             =back
408            
409             =item * INTERACTION
410            
411             Lets you define subs used to interact with the user.
412            
413             INTERACTION =>
414             {
415             INFO => \&sub,
416             WARN => \&sub,
417             DIE => \&sub,
418             EVAL_DIE => \&sub,
419             }
420            
421             =over 6
422            
423             =item INFO - defaults to CORE::print
424            
425             This sub will be used when displaying information.
426            
427             =item WARN - defaults to Carp::carp
428            
429             This sub will be used when a warning is displayed.
430            
431             =item DIE - defaults to Carp::confess
432            
433             Used when an error occurs.
434            
435             =item EVAL_DIE - defaults to Carp::confess, with a dump of the code to be evaluated
436            
437             Used when an error occurs during code evaluation.
438            
439             =back
440            
441             =item * FILE - the file where the object has been created.
442            
443             This is practical if you want to wrap the object.
444            
445             B<FILE> and B<LINE> will be set automatically if not set.
446            
447             =item * LINE - the line where the object has been created. Set automatically if not set.
448            
449             =item * DISPLAY_SOURCE_IN_CONTEXT - if set, the code to evaluated will be displayed before evaluation
450            
451             =back
452            
453             =back
454            
455             I<Return>
456            
457             =over 2
458            
459             =item * an B<Eval::Context> object.
460            
461             =back
462            
463             =cut
464              
465 3     3 1 1428 my ($invocant, @setup_data) = @_ ;
466              
467 3   100     15 my $class = ref($invocant) || $invocant ;
468 3 100       24 confess 'Invalid constructor call!' unless defined $class ;
469              
470 2         3 my $object = {} ;
471              
472 2         9 my ($package, $file_name, $line) = caller() ;
473 2         38 bless $object, $class ;
474              
475 2         9 $object->Setup($package, $file_name, $line, @setup_data) ;
476              
477 2         5 return($object) ;
478             }
479              
480             #-------------------------------------------------------------------------------
481              
482             sub Setup
483             {
484              
485             =head2 [p] Setup
486            
487             Helper sub called by new.
488            
489             =cut
490              
491 2     2 1 4 my ($self, $package, $file_name, $line, @setup_data) = @_ ;
492              
493 2         8 my $inital_option_checking_context = { NAME => 'Anonymous eval context', FILE => $file_name, LINE => $line,} ;
494 2         6 SetInteractionDefault($inital_option_checking_context) ;
495              
496 2         6 CheckOptionNames
497             (
498             $inital_option_checking_context,
499             $NEW_ARGUMENTS,
500             @setup_data
501             ) ;
502              
503 2         3 %{$self} =
  2         12  
504             (
505             NAME => 'Anonymous',
506             FILE => $file_name,
507             LINE => $line,
508             REMOVE_PACKAGE_AFTER_EVAL => 1,
509            
510             @setup_data,
511             ) ;
512              
513 2 50 33     12 if((! defined $self->{NAME}) || $self->{NAME} eq $EMPTY_STRING)
514             {
515 0         0 $self->{NAME} = 'Anonymous eval context' ;
516             }
517              
518 2         18 SetInteractionDefault($self) ;
519              
520 2         17 return(1) ;
521             }
522              
523             #-------------------------------------------------------------------------------
524              
525             sub CheckOptionNames
526             {
527              
528             =head2 [p] CheckOptionNames
529            
530             Verifies the named options passed as arguments with a list of valid options. Calls B<{INTERACTION}{DIE}> in case
531             of error.
532            
533             =cut
534              
535 2     2 1 27 my ($self, $valid_options, @options) = @_ ;
536              
537 2 50       17 if (@options % 2)
538             {
539 0         0 $self->{INTERACTION}{DIE}->($self, "Invalid number of argument at '$self->{FILE}:$self->{LINE}'!") ;
540             }
541              
542 2 50       9 if('HASH' eq ref $valid_options)
    50          
543             {
544             # OK
545             }
546             elsif('ARRAY' eq ref $valid_options)
547             {
548 2         5 $valid_options = {map{$_ => 1} @{$valid_options}} ;
  28         56  
  2         5  
549             }
550             else
551             {
552 0         0 $self->{INTERACTION}{DIE}->($self, q{Invalid 'valid_options' definition! Should be an array or hash reference.}) ;
553             }
554              
555 2         8 my %options = @options ;
556              
557 2         7 for my $option_name (keys %options)
558             {
559 0 0       0 unless(exists $valid_options->{$option_name})
560             {
561 0         0 $self->{INTERACTION}{DIE}->($self, "$self->{NAME}: Invalid Option '$option_name' at '$self->{FILE}:$self->{LINE}'!") ;
562             }
563             }
564              
565 2 50 33     33 if
      33        
      33        
566             (
567             (defined $options{FILE} && ! defined $options{LINE})
568             || (!defined $options{FILE} && defined $options{LINE})
569             )
570             {
571 0         0 $self->{INTERACTION}{DIE}->($self, "$self->{NAME}: Incomplete option FILE::LINE!") ;
572             }
573              
574 2         8 return(1) ;
575             }
576              
577             #-------------------------------------------------------------------------------
578              
579             sub SetInteractionDefault
580             {
581            
582             =head2 [p] SetInteractionDefault
583            
584             Sets {INTERACTION} fields that are not set by the user.
585            
586             =cut
587              
588 4     4 1 7 my ($interaction_container) = @_ ;
589              
590 4   50 0   30 $interaction_container->{INTERACTION}{INFO} ||= sub {my (@information) = @_ ; print @information} ; ## no critic (InputOutput::RequireCheckedSyscalls)
  0         0  
  0         0  
591 4   50     19 $interaction_container->{INTERACTION}{WARN} ||= \&Carp::carp ;
592 4   50 0   29 $interaction_container->{INTERACTION}{DIE}  ||= sub { my($self, @error) = @_ ; Carp::confess(@error)} ;
  0         0  
  0         0  
593              
594             $interaction_container->{INTERACTION}{EVAL_DIE}  ||=
595             sub {
596 0     0   0 my($self, $error) = @_ ;
597 0         0 Carp::confess
598             (
599             "*** Eval::Context code ***\n"
600             . $self->{LATEST_CODE}
601             . "\n*** Error below ***\n"
602             . $error
603             ) ;
604 4   50     33 }  ;
605              
606 4         6 return ;
607             }
608              
609             #-------------------------------------------------------------------------------
610              
611             sub CanonizeName
612             {
613            
614             =head2 [p] CanonizeName
615            
616             Transform a string into a a string with can be used as a package name or file name usable
617             within perl code.
618            
619             =cut
620              
621 0     0 1   my ($name) = @_ ;
622              
623 0 0         croak 'CanonizeName called with undefined argument!' unless defined $name ;
624              
625 0           $name =~ s/[^a-zA-Z0-9_:\.]/_/xsmg ;
626              
627 0           return($name) ;
628             }
629              
630             #-------------------------------------------------------------------------------
631              
632             Readonly my $EVAL_ARGUMENTS => [@{$NEW_ARGUMENTS}, qw(CODE CODE_FROM_FILE REMOVE_PERSISTENT)] ;
633              
634             sub eval ## no critic (Subroutines::ProhibitBuiltinHomonyms ErrorHandling::RequireCheckingReturnValueOfEval)
635             {
636              
637             =head2 eval(@named_arguments)
638            
639             Evaluates Perl code, passed as a string or read from a file, in the context.
640            
641             my $context = new Eval::Context(PRE_CODE => "use strict;\nuse warnings;\n") ;
642            
643             $context->eval(CODE => 'print "evaluated in an Eval::Context!";') ;
644             $context->eval(CODE_FROM_FILE => 'file.pl') ;
645            
646             I<Call context>
647            
648             Evaluation context of the code (void, scalar, list) is the same as the context this subroutine was called in
649             or in the context defined by B<PERL_EVAL_CONTEXT> if that option is present.
650            
651             I<Arguments>
652            
653             B<NOTE: You can override any argument passed to >C<new>B<. The override is temporary during
654             the duration of this call.>
655            
656             =over 2
657            
658             =item * @named_arguments - Any of C<new> options plus the following.
659            
660             =over 4
661            
662             =item * CODE - a string containing perl code (valid code or an exception is raised)
663            
664             =item * CODE_FROM_FILE - a file containing perl code
665            
666             =item * REMOVE_PERSISTENT
667            
668             A list of regex used to match the persistent variable names to be removed, persistent variable removal
669             is done before any variable installation is done
670            
671             =item * FILE and LINE - will be used in the evaluated code 'file_name' set to the caller's file and line by default
672            
673             =back
674            
675             NOTE: B<CODE> or B<CODE_FROM_FILE> is B<mandatory>.
676            
677             =back
678            
679             I<Return>
680            
681             =over 2
682            
683             =item * What the code to be evaluated returns
684            
685             =back
686            
687             =cut
688              
689 0     0 1   my ($self, @options) = @_ ;
690              
691 0           my $options = $self->VerifyAndCompleteOptions($EVAL_ARGUMENTS, @options) ;
692              
693 0 0         $options->{PERL_EVAL_CONTEXT} = wantarray unless exists $options->{PERL_EVAL_CONTEXT} ;
694              
695 0           my ($package, $variables_setup, $variables_teardown) = $self->EvalSetup($options) ;
696              
697 0           my ($code_start, $code_end, $return) = $self->GetCallContextWrapper($variables_setup, $options) ;
698              
699 0           my ($package_setup, $compartment, $compartment_use_strict, $pre_code_commented_out)
700             = $self->SetupSafeCompartment($package, $options) ;
701              
702 0           $self->VerifyCodeInput($options) ;
703              
704 0           $self->{LATEST_CODE} = "#line 0 '$options->{EVAL_FILE_NAME}'\n" ;
705              
706 0           for
707             (
708             $package_setup,
709             $pre_code_commented_out,
710             '# PRE_CODE',
711             $options->{PRE_CODE},
712             $variables_setup,
713             $code_start,
714             "#line 0 '$options->{EVAL_FILE_NAME}'",
715             '# CODE',
716             $options->{CODE},
717             '# POST_CODE',
718             $options->{POST_CODE},
719             $code_end,
720             $variables_teardown,
721             $return,
722             "#end of context '$options->{EVAL_FILE_NAME}'",
723             )
724             {
725 0 0         $self->{LATEST_CODE} .= "$_\n" if defined $_ ;
726             }
727              
728 0 0         if($options->{DISPLAY_SOURCE_IN_CONTEXT})
729             {
730 0           $options->{INTERACTION}{INFO}
731             ->("Eval::Context called at '$options->{FILE}:$options->{LINE}' to evaluate:\n" . $self->{LATEST_CODE}) ;
732             }
733            
734 0 0         if(defined $options->{PERL_EVAL_CONTEXT})
735             {
736 0 0         if($options->{PERL_EVAL_CONTEXT})
737             {
738 0 0         my  @results =
739             $compartment
740             ? $compartment->reval($self->{LATEST_CODE}, $compartment_use_strict)
741             : eval $self->{LATEST_CODE} ; ## no critic (BuiltinFunctions::ProhibitStringyEval)
742            
743 0 0         $options->{INTERACTION}{EVAL_DIE}->($self, $EVAL_ERROR) if($EVAL_ERROR) ;
744 0           $self->EvalCleanup($options) ;
745            
746 0           return @results ;
747             }
748             else
749             {
750 0 0         my $result =
751             $compartment
752             ? $compartment->reval($self->{LATEST_CODE}, $compartment_use_strict)
753             : eval $self->{LATEST_CODE} ; ## no critic (BuiltinFunctions::ProhibitStringyEval)
754            
755 0 0         $options->{INTERACTION}{EVAL_DIE}->($self, $EVAL_ERROR) if($EVAL_ERROR) ;
756 0           $self->EvalCleanup($options) ;
757            
758 0           return $result ;
759             }
760             }
761             else
762             {
763 0 0         defined $compartment
764             ? $compartment->reval($self->{LATEST_CODE}, $compartment_use_strict)
765             : eval $self->{LATEST_CODE} ; ## no critic (BuiltinFunctions::ProhibitStringyEval)
766            
767 0 0         $options->{INTERACTION}{EVAL_DIE}->($self, $EVAL_ERROR) if($EVAL_ERROR) ;
768 0           $self->EvalCleanup($options) ;
769            
770 0           return ;
771             }
772             }
773              
774             #-------------------------------------------------------------------------------
775              
776             sub VerifyAndCompleteOptions
777             {
778              
779             =head2 [p] VerifyAndCompleteOptions
780            
781             Helper sub for C<eval>.
782            
783             =cut
784              
785 0     0 1   my ($self, $allowed_arguments, @options) = @_ ;
786              
787 0           $self->CheckOptionNames($allowed_arguments, @options) ;
788              
789 0           my %options = @options ;
790              
791 0 0         unless(defined $options{FILE})
792             {
793 0           my ($package, $file_name, $line) = caller(1) ;
794 0           push @options, FILE => $file_name, LINE => $line
795             }
796            
797 0           %options = (%{$self}, @options) ;
  0            
798              
799 0           $options{NAME} = CanonizeName($options{NAME} . " called at $options{FILE}:$options{LINE}") ;
800              
801 0           SetInteractionDefault(\%options) ;
802              
803 0           return(\%options) ;
804             }
805              
806             #-------------------------------------------------------------------------------
807              
808             sub EvalCleanup
809             {
810              
811             =head2 [p] EvalCleanup
812            
813             Handles the package cleanup or persistent variables cleanup after a call to C<eval>.
814            
815             =cut
816              
817 0     0 1   my ($self, $options) = @_ ;
818              
819 0 0         if($options->{REMOVE_PACKAGE_AFTER_EVAL})
820             {
821 0           delete_package($self->{CURRENT_RUNNING_PACKAGE})
822             }
823             else
824             {
825 0 0         if(defined $options->{EVAL_SIDE_PERSISTENT_VARIABLES})
826             {
827 0           $self->RemoveEvalSidePersistenceHandlers($options) ;
828             }
829             }
830              
831 0           return(1) ;
832             }
833              
834             #-------------------------------------------------------------------------------
835              
836             my $eval_run = 0 ;
837              
838             sub GetPackageName
839             {
840              
841             =head2 [p] GetPackageName
842            
843             Returns a canonized package name. the name is either passed as argument from the caller
844             or a temporary package name.
845            
846             =cut
847              
848 0     0 1   my ($options) = @_ ;
849              
850 0 0 0       my $package = exists $options->{PACKAGE} && defined $options->{PACKAGE}
851             ? CanonizeName($options->{PACKAGE})
852             : "Eval::Context::Run_$eval_run" ;
853              
854 0 0         $package = $package eq $EMPTY_STRING ? "Eval::Context::Run_$eval_run" : $package ;
855              
856 0           $eval_run++ ;
857              
858 0           return($package) ;
859             }
860              
861             #-------------------------------------------------------------------------------
862              
863             sub EvalSetup
864             {
865              
866             =head2 [p] EvalSetup
867            
868             Handles the setup of the context before I<eval-side> code is evaluated. Sets
869             the variables and the shared subroutines.
870            
871             =cut
872              
873 0     0 1   my ($self, $options) = @_ ;
874              
875 0           my $package = $self->{CURRENT_RUNNING_PACKAGE} = GetPackageName($options) ;
876              
877 0           $self->RemovePersistent($options) ;
878              
879 0           my ($variables_setup, $variables_teardown) = (undef, undef) ;
880              
881 0 0         if(defined $options->{INSTALL_VARIABLES})
882             {
883 0           ($variables_setup, $variables_teardown) = $self->GetInstalledVariablesCode($options) ;
884             }
885              
886 0           for my $sub_name (keys %{$options->{INSTALL_SUBS}})
  0            
887             {
888 0 0         if('CODE' ne ref $options->{INSTALL_SUBS}{$sub_name} )
889             {
890 0           $options->{INTERACTION}{DIE}->($self, "$self->{NAME}: '$sub_name' from 'INSTALL_SUBS' isn't a code reference at '$options->{FILE}:$options->{LINE}'!") ;
891             }
892            
893 0           reinstall_sub({ code => $options->{INSTALL_SUBS}{$sub_name}, into => $package, as => $sub_name }) ;
894             }
895            
896 0 0         if(defined $options->{EVAL_SIDE_PERSISTENT_VARIABLES})
897             {
898 0           $self->SetEvalSidePersistenceHandlers($options) ;
899             }
900              
901 0           return ($package, $variables_setup, $variables_teardown) ;
902             }
903              
904             #-------------------------------------------------------------------------------
905              
906             sub VerifyCodeInput
907             {
908              
909             =head2 [p] VerifyCodeInput
910            
911             Verify that B<CODE> or B<CODE_FROM_FILE> are properly set.
912            
913             =cut
914              
915 0     0 1   my ($self, $options) = @_ ;
916              
917 0   0       $options->{EVAL_FILE_NAME} = $options->{NAME} || 'Anonymous' ;
918              
919 0 0         $options->{PRE_CODE} = defined $options->{PRE_CODE} ? $options->{PRE_CODE} : $EMPTY_STRING ;
920              
921 0 0 0       if(exists $options->{CODE_FROM_FILE} && exists $options->{CODE} )
922             {
923 0           $options->{INTERACTION}{DIE}->($self, "$self->{NAME}: Option 'CODE' and 'CODE_FROM_FILE' can't coexist at '$options->{FILE}:$options->{LINE}'!") ;
924             }
925              
926 0 0 0       if(exists $options->{CODE_FROM_FILE} && defined $options->{CODE_FROM_FILE})
927             {
928 0           $options->{CODE} = read_file($options->{CODE_FROM_FILE}) ;
929 0           $options->{NAME} = CanonizeName($options->{CODE_FROM_FILE}) ;
930 0           $options->{EVAL_FILE_NAME} = $options->{CODE_FROM_FILE} ;
931             }
932              
933 0 0 0       unless(exists $options->{CODE} && defined $options->{CODE})
934             {
935 0           $options->{INTERACTION}{DIE}->($self, "$self->{NAME}: Invalid Option 'CODE' at '$options->{FILE}:$options->{LINE}'!") ;
936             }
937              
938 0 0         $options->{POST_CODE} = defined $options->{POST_CODE} ? $options->{POST_CODE} : $EMPTY_STRING ;
939              
940 0           return(1) ;
941             }
942              
943             #-------------------------------------------------------------------------------
944              
945             sub RemovePersistent
946             {
947              
948             =head2 [p] RemovePersistent
949            
950             Handles the removal of persistent variables.
951            
952             =cut
953              
954 0     0 1   my ($self, $options) = @_ ;
955              
956 0 0         if(exists $options->{REMOVE_PERSISTENT})
957             {
958 0 0         if('ARRAY' ne ref $options->{REMOVE_PERSISTENT})
959             {
960 0           $options->{INTERACTION}{DIE}->
961             (
962             $self,
963             "$self->{NAME}: 'REMOVE_PERSISTENT' must be an array reference containing regexes at '$options->{FILE}:$options->{LINE}'!"
964             )  ;
965             }
966            
967 0           for my $regex (@{ $options->{REMOVE_PERSISTENT} })
  0            
968             {
969 0           for my $name ( keys %{ $self->{PERSISTENT_VARIABLES} })
  0            
970             {
971 0 0         delete $self->{PERSISTENT_VARIABLES}{$name} if($name =~ $regex) ;
972             }
973             }
974             }
975            
976 0           return(1) ;
977             }
978              
979             #-------------------------------------------------------------------------------
980              
981             sub GetCallContextWrapper
982             {
983              
984             =head2 [p] GetCallContextWrapper
985            
986             Generates perl code to wrap the code to be evaluated in the right calling context.
987            
988             =cut
989              
990 0     0 1   my ($self, $variables_setup, $options) = @_ ;
991              
992 0           my ($code_start, $code_end, $return) = (undef, undef, undef) ; # defaults for void context
993              
994 0 0         if(defined $variables_setup)
995             {
996 0 0         if(defined $options->{PERL_EVAL_CONTEXT})
997             {
998 0 0         if($options->{PERL_EVAL_CONTEXT})
999             {
1000             # array context
1001 0           ($code_start, $code_end, $return) =
1002             (
1003             "my \@eval_context_result = do {\n",
1004             "} ;\n",
1005             "\@eval_context_result ;\n",
1006             ) ;
1007             }
1008             else
1009             {
1010             # scalar context
1011 0           ($code_start, $code_end, $return) =
1012             (
1013             "my \$eval_context_result = do {\n",
1014             "} ;\n",
1015             "\$eval_context_result ;\n",
1016             ) ;
1017             }
1018             }
1019             else
1020             {
1021             # void context
1022 0           ($code_start, $code_end, $return) = ($EMPTY_STRING, $EMPTY_STRING, $EMPTY_STRING) ;
1023             }
1024             }
1025              
1026 0           return($code_start, $code_end, $return) ;
1027             }
1028              
1029             #-------------------------------------------------------------------------------
1030            
1031             sub SetupSafeCompartment
1032             {
1033              
1034             =head2 [p] SetupSafeCompartment
1035            
1036             If running in safe mode, setup a safe compartment from the argument, otherwise defines the evaluation package.
1037            
1038             =cut
1039              
1040 0     0 1   my ($self, $package, $options) = @_ ;
1041              
1042 0           my ($package_setup, $compartment, $compartment_use_strict, $pre_code_commented_out) = (undef, undef, 1, undef) ;
1043              
1044 0 0         if(exists $options->{SAFE})
1045             {
1046 0 0         if('HASH' eq ref $options->{SAFE})
1047             {
1048 0 0         if(exists $options->{SAFE}{PRE_CODE})
1049             {
1050             # must be done before creating the safe compartment
1051 0           my $pre_code = "\npackage " . $package . " ;\n" . $options->{SAFE}{PRE_CODE} ;
1052            
1053 0           eval $pre_code ; ## no critic (BuiltinFunctions::ProhibitStringyEval)
1054            
1055 0 0         if($EVAL_ERROR) 
1056             {
1057 0           $self->{LATEST_CODE} = $pre_code ;
1058 0           $options->{INTERACTION}{EVAL_DIE}->($self, $EVAL_ERROR) ;
1059             }
1060            
1061             $pre_code_commented_out =
1062 0           "# Note: evaluated PRE_CODE before running SAFE code\n" 
1063             . "=comment\n\n"
1064             . $pre_code
1065             . "\n\n=cut\n" ;
1066             }
1067            
1068 0 0         if(exists $options->{SAFE}{COMPARTMENT})
1069             {
1070 0           $compartment = $options->{SAFE}{COMPARTMENT} ;
1071             }
1072             else
1073             {
1074 0           $compartment = new Safe($package) ;
1075             }
1076            
1077 0 0         $compartment_use_strict = $options->{SAFE}{USE_STRICT} if exists $options->{SAFE}{USE_STRICT} ;
1078             }
1079             else
1080             {
1081 0           $options->{INTERACTION}{DIE}->($self, "$self->{NAME}: Invalid Option 'SAFE' definition at '$options->{FILE}:$options->{LINE}'!") ;
1082             }
1083              
1084             }
1085             else
1086             {
1087 0           $package_setup = "package $package ;"
1088             }
1089            
1090 0           return($package_setup, $compartment, $compartment_use_strict, $pre_code_commented_out) ;
1091             }
1092              
1093             #-------------------------------------------------------------------------------
1094              
1095             Readonly my $SET_FROM_CALLER => 2 ;
1096             Readonly my $SET_FROM_CALLER_WITH_TYPE => 3 ;
1097              
1098             Readonly my $NAME_INDEX => 0 ;
1099             Readonly my $VALUE_INDEX => 1 ;
1100             Readonly my $TYPE_INDEX => 2 ;
1101              
1102             sub GetInstalledVariablesCode
1103             {
1104              
1105             =head2 [p] GetInstalledVariablesCode
1106            
1107             Generates variables on the eval-side from the INSTALL_VARIABLES definitions.
1108             Dispatches the generation to specialize subroutines.
1109            
1110             =cut
1111              
1112 0     0 1   my ($self, $options) = @_ ;
1113              
1114 0           my ($setup_code, $teardown_code) = ($EMPTY_STRING, $EMPTY_STRING) ;
1115              
1116 0           for my $variable_definition (@{ $options->{INSTALL_VARIABLES} })
  0            
1117             {
1118 0           my $definition_type = scalar(@{$variable_definition}) ;
  0            
1119            
1120 0           my $variable_name = $variable_definition->[$NAME_INDEX] ;
1121 0           my $variable_value = $variable_definition->[$VALUE_INDEX] ;
1122 0           my $variable_type = ref $variable_value ;
1123            
1124 0 0         if($SET_FROM_CALLER == $definition_type)
    0          
1125             {
1126 0           my ($setup, $teardown) = $self->GetVariablesSetFromCaller($options, $variable_name, $variable_value, $variable_type) ;
1127            
1128 0           $setup_code .= $setup ;
1129 0           $teardown_code .= $teardown ;
1130             }
1131             elsif($SET_FROM_CALLER_WITH_TYPE == $definition_type)
1132             {
1133 0 0         if($variable_definition->[$TYPE_INDEX] == $PERSISTENT)
    0          
1134             {
1135 0           my ($setup, $teardown) = $self->GetPersistentVariablesSetFromCaller
1136             (
1137             $options,
1138             $variable_name,
1139             $variable_value,
1140             $variable_type,
1141             ) ;
1142            
1143 0           $setup_code .= $setup ;
1144 0           $teardown_code .= $teardown ;
1145             }
1146             elsif($variable_definition->[$TYPE_INDEX] == $SHARED)
1147             {
1148 0           my ($setup, $teardown) = $self->GetSharedVariablesSetFromCaller
1149             (
1150             $options,
1151             $variable_name,
1152             $variable_value,
1153             $variable_type,
1154             ) ;
1155            
1156 0           $setup_code .= $setup ;
1157 0           $teardown_code .= $teardown ;
1158             }
1159             else
1160             {
1161 0           $self->{INTERACTION}{DIE}->($self, "Variable '$variable_name' type must be SHARED or PERSISTENT at '$options->{FILE}:$options->{LINE}'!") ;
1162             }
1163             }
1164             else
1165             {
1166 0           $self->{INTERACTION}{DIE}->($self, "Invalid variable definition at '$options->{FILE}:$options->{LINE}'!") ;
1167             }
1168             }
1169              
1170 0           return($setup_code, $teardown_code) ;
1171             }
1172              
1173             #-------------------------------------------------------------------------------
1174              
1175             my $temporary_name_index = 0 ;
1176              
1177             sub GetPersistentVariablesSetFromCaller
1178             {
1179            
1180             =head2 [p] GetPersistentVariablesSetFromCaller
1181            
1182             Generates code to make persistent variables, defined on the I<caller-side> available on the I<eval-side>.
1183            
1184             =cut
1185              
1186 0     0 1   my ($self, $options, $variable_name, $variable_value, $variable_type) = @_ ;
1187              
1188 0           my $persistance_handler_name = 'EvalContextSavePersistentVariable' ;
1189              
1190 0           my ($setup_code, $teardown_code) = ($EMPTY_STRING, $EMPTY_STRING) ;
1191              
1192 0 0         if(exists $self->{SHARED_VARIABLES}{$variable_name})
1193             {
1194 0           $self->{INTERACTION}{DIE}->($self, "'$variable_name' can't be PERSISTENT, already SHARED, at '$options->{FILE}:$options->{LINE}'!") ;
1195             }
1196              
1197 0 0         if(! exists $self->{PERSISTENT_VARIABLES}{$variable_name})
1198             {
1199 0           ($setup_code, undef) = $self->GetVariablesSetFromCaller($options, $variable_name, $variable_value, $variable_type) ;
1200 0           $setup_code = "# PERSISTENT, did not exist '$variable_name'\n" . $setup_code ;
1201             }
1202             else
1203             {
1204 0 0         if(ref $variable_value eq 'USE_PERSISTENT')
1205             {
1206 0           $setup_code = "# PERSISTENT, existed '$variable_name'\n"
1207             . "my $self->{PERSISTENT_VARIABLES}{$variable_name}\n" ;
1208             }
1209             else
1210             {
1211 0           ($setup_code, undef) = $self->GetVariablesSetFromCaller($options, $variable_name, $variable_value, $variable_type) ;
1212 0           $setup_code = "# PERSISTENT, existed '$variable_name', overridden \n" . $setup_code ;
1213             }
1214             }
1215            
1216             # save the persistent variables after the user code is run
1217 0           $teardown_code = "$persistance_handler_name('$variable_name', \\$variable_name) ;\n" ;
1218              
1219             # install the subroutines needed to save the persistent variables
1220             reinstall_sub
1221             ({
1222             code => sub
1223             {
1224 0     0     my ($variable_name, $variable_ref) = @_ ;
1225            
1226 0           my $dump_name = $variable_name ;
1227 0           substr($dump_name, 0, 1, $EMPTY_STRING) ;
1228            
1229 0 0         if('SCALAR' eq ref $variable_ref)
    0          
1230             {
1231 0 0         if(defined ${$variable_ref})
  0            
1232             {
1233 0           $self->{PERSISTENT_VARIABLES}{$variable_name} = "$variable_name = '${$variable_ref}' ;" ;
  0            
1234             }
1235             else
1236             {
1237 0           $self->{PERSISTENT_VARIABLES}{$variable_name} = "$variable_name = undef ;" ;
1238             }
1239             }
1240             elsif('REF' eq ref $variable_ref)
1241             {
1242 0           $self->{PERSISTENT_VARIABLES}{$variable_name} = Data::Dumper->Dump([${$variable_ref}], [$dump_name]) ;
  0            
1243             }
1244             else
1245             {
1246             # convert and serialize at once
1247 0           my ($sigil, $name) = $variable_name =~ /(.)(.*)/sxm ;
1248            
1249 0           $self->{PERSISTENT_VARIABLES}{$variable_name} = Data::Dumper->Dump([$variable_ref], [$name]) ;
1250 0           $self->{PERSISTENT_VARIABLES}{$variable_name} =~ s/\$$name\ =\ ./$variable_name = (/xsm ;
1251 0           $self->{PERSISTENT_VARIABLES}{$variable_name} =~ s/.;\Z/) ;/xsm ;
1252             }
1253             },
1254            
1255 0           into => $self->{CURRENT_RUNNING_PACKAGE},
1256             as => $persistance_handler_name,
1257             }) ;
1258            
1259 0           return($setup_code, $teardown_code) ;
1260             }
1261              
1262             #-------------------------------------------------------------------------------
1263              
1264             our %shared_variables ; ## no critic (Variables::ProhibitPackageVars)
1265              
1266             sub GetSharedVariablesSetFromCaller
1267             {
1268              
1269             =head2 [p] GetSharedVariablesSetFromCaller
1270            
1271             Handles the mechanism used to share variables (references) between the I<caller-side>
1272             and the I<eval-side>.
1273            
1274             Shared variables must be defined and references. If the shared variable is B<undef>, the variable
1275             that was previously shared, under the passed name, is used if it exists or an exception is raised.
1276            
1277             Also check that variables are not B<PERSISTENT> and B<SHARED>.
1278            
1279             =cut
1280              
1281 0     0 1   my ($self, $options, $variable_name, $variable_value, $variable_type) = @_ ;
1282              
1283 0           my ($setup_code, $teardown_code) = ($EMPTY_STRING, $EMPTY_STRING) ;
1284              
1285 0 0         if(exists $self->{PERSISTENT_VARIABLES}{$variable_name})
1286             {
1287 0           $self->{INTERACTION}{DIE}->($self, "'$variable_name' can't be SHARED, already PERSISTENT, at '$options->{FILE}:$options->{LINE}'!") ;
1288             }
1289              
1290 0 0         if(defined $variable_value)
1291             {
1292 0 0         if($EMPTY_STRING eq ref $variable_value)
1293             {
1294 0           $self->{INTERACTION}{DIE}->($self, "Need a reference to share from for '$variable_name' at '$options->{FILE}:$options->{LINE}'!") ;
1295             }
1296              
1297 0           my $variable_share_name = "${variable_name}_$self->{FILE}_$self->{LINE}_$temporary_name_index" ;
1298 0           $variable_share_name =~ s/[^a-zA-Z0-9_]+/_/xsmg ;
1299 0           $temporary_name_index++ ;
1300            
1301 0           $shared_variables{$variable_share_name} = $variable_value ;
1302            
1303 0 0         if(exists $options->{SAFE})
1304             {
1305 0           $self->{SHARED_VARIABLES}{$variable_name} = $variable_share_name ;
1306             }
1307             else
1308             {
1309             # faster method
1310 0           $self->{SHARED_VARIABLES}{$variable_name} = q{$} . __PACKAGE__ . "::shared_variables{$variable_share_name}" ;
1311             }
1312             }
1313            
1314 0 0         if(exists $self->{SHARED_VARIABLES}{$variable_name})
1315             {
1316 0 0         if(exists $options->{SAFE})
1317             {
1318 0           $setup_code = "my $variable_name = EvalContextSharedVariable('$self->{SHARED_VARIABLES}{$variable_name}') ;\n" ;
1319            
1320 0     0     reinstall_sub({
1321 0           code => sub {my ($variable_name) = @_ ; return($shared_variables{$variable_name}) ;},
1322 0           into => $self->{CURRENT_RUNNING_PACKAGE},
1323             as => 'EvalContextSharedVariable',
1324             }) ;
1325             }
1326             else
1327             {
1328 0           $setup_code = "my $variable_name = $self->{SHARED_VARIABLES}{$variable_name} ;\n" ; # not in Safe, we can access other packages
1329             }
1330             }
1331             else
1332             {
1333 0           $self->{INTERACTION}{DIE}->($self, "Nothing previously shared to '$variable_name' at '$options->{FILE}:$options->{LINE}'!") ;
1334             }
1335            
1336 0           return($setup_code, $teardown_code) ;
1337             }
1338              
1339             #-------------------------------------------------------------------------------
1340              
1341             my %valid_sigil = map {$_ => 1} qw($ @ %) ;
1342              
1343             sub GetVariablesSetFromCaller
1344             {
1345            
1346             =head2 [p] GetVariablesSetFromCaller
1347            
1348             Generates code that creates local variables on the I<eval-side>
1349            
1350             =cut
1351              
1352 0     0 1   my ($self, $options, $variable_name, $variable_value, $variable_type) = @_ ;
1353              
1354 0           my $DIE = $self->{INTERACTION}{DIE} ;
1355 0           my $code_to_evaluate = $EMPTY_STRING ;
1356              
1357 0           my ($sigil, $name) = $variable_name =~ /(.)(.*)/sxm ;
1358 0 0         $DIE->($self, "Invalid variable type for '$variable_name' at '$options->{FILE}:$options->{LINE}'!") unless $valid_sigil{$sigil} ;
1359              
1360 0 0         if(! defined $variable_value)
1361             {
1362 0           $code_to_evaluate .= "my $variable_name = undef ;\n" ;
1363             }
1364             else
1365             {
1366 0 0         if($EMPTY_STRING eq $variable_type)
1367             {
1368 0           $code_to_evaluate .= "my $variable_name = '$variable_value';\n" ;
1369             }
1370             else
1371             {
1372             # set from reference
1373 0           my $conversion = $EMPTY_STRING ;
1374            
1375 0 0         if($sigil eq q{$})
1376             {
1377             # reference to reference, no conversion needed
1378 0           $conversion = Data::Dumper->Dump([$variable_value], [$variable_name] ) ;
1379             }
1380             else
1381             {
1382 0           $conversion = Data::Dumper->Dump([$variable_value], [$name]) ;
1383 0           $conversion =~ s/\A\$$name\ =\ ./$variable_name = (/xsm ;
1384 0           $conversion =~ s/.;\Z/) ;/xsm ;
1385             }
1386            
1387 0           $code_to_evaluate .= "my $conversion" ;
1388             }
1389             }
1390            
1391 0           return($code_to_evaluate, $EMPTY_STRING) ;
1392             }
1393              
1394             #-------------------------------------------------------------------------------
1395              
1396             sub GetPersistentVariableNames
1397             {
1398              
1399             =head2 GetPersistentVariableNames()
1400            
1401             I<Arguments> - none
1402            
1403             I<Returns> - the list of existing persistent variables names
1404            
1405             my @persistent_variable_names = $context->GetPersistantVariablesNames() ;
1406            
1407             =cut
1408              
1409 0     0 1   my ($self) = @_ ;
1410              
1411 0           return(keys %{ $self->{PERSISTENT_VARIABLES} }) ;
  0            
1412             }
1413              
1414             #-------------------------------------------------------------------------------
1415              
1416             sub GetPersistantVariables
1417             {
1418              
1419             =head2 GetPersistantVariables(@variable_names)
1420            
1421             I<Arguments>
1422            
1423             =over 2
1424            
1425             =item * @variable_names - list of variable names to retrieve
1426            
1427             =back
1428            
1429             I<Returns> - list of values corresponding to the input names
1430            
1431             This subroutine will return whatever the I<caller-site> set or the I<eval-side> modified. Thus if
1432             you created a I<%hash> persistent variable, a hash (not a hash reference) will be returned.
1433            
1434             If you request multiple values, list flattening will be in effect. Be careful.
1435            
1436             my $context = new Eval::Context
1437             (
1438             INSTALL_VARIABLES =>
1439             [
1440             ['%hash' => \%hash_caller_side => $Eval::Context::PERSISTENT]
1441             ] ,
1442             ) ;
1443            
1444             $context->Eval(CODE => '$hash{A}++ ;') ;
1445            
1446             # may throw exception
1447             my %hash_after_eval = $context->GetPersistantVariables('%hash') ;
1448            
1449             =cut
1450              
1451 0     0 1   my ($self, @variable_names) = @_ ;
1452              
1453 0           my ($package, $file_name, $line) = caller() ;
1454 0           my @values ;
1455              
1456 0           for my $variable_name (@variable_names)
1457             {
1458 0 0         if(exists $self->{PERSISTENT_VARIABLES}{$variable_name})
1459             {
1460 0           my @variable_values = eval 'my ' . $self->{PERSISTENT_VARIABLES}{$variable_name} ; ## no critic (BuiltinFunctions::ProhibitStringyEval)
1461 0           push @values, @variable_values ;
1462             }
1463             else
1464             {
1465 0           $self->{INTERACTION}{DIE}->
1466             (
1467             $self,
1468             "PERSISTENT variable '$variable_name' doesn't exist, can't be fetched at '$file_name:$line'!"
1469             ) ;
1470             }
1471             }
1472              
1473 0 0         if(defined wantarray)
1474             {
1475 0 0         if(wantarray)
1476             {
1477 0           return(@values) ;
1478             }
1479             else
1480             {
1481 0           return $values[0] ;
1482             }
1483             }
1484             else
1485             {
1486             return #PBP
1487             (
1488 0           $self->{INTERACTION}{DIE}->
1489             (
1490             $self,
1491             "GetPersistantVariables called in void context at '$file_name:$line'!"
1492             ) 
1493             )
1494             }
1495             }
1496              
1497             #-------------------------------------------------------------------------------
1498              
1499             sub SetEvalSidePersistenceHandlers
1500             {
1501              
1502             =head2 [p] SetEvalSidePersistenceHandlers
1503            
1504             Set the code needed to handle I<eval-side> persistent variables.
1505            
1506             =cut
1507              
1508 0     0 1   my ($self, $options) = @_ ;
1509              
1510 0 0         if('HASH' eq ref $options->{EVAL_SIDE_PERSISTENT_VARIABLES})
1511             {
1512 0 0         my $category = defined $options->{EVAL_SIDE_PERSISTENT_VARIABLES}{CATEGORY}
1513             ? $options->{EVAL_SIDE_PERSISTENT_VARIABLES}{CATEGORY}
1514             : $self->{CURRENT_RUNNING_PACKAGE} ;
1515            
1516 0           my %handler_sub_validators ;
1517             my %handler_subs =
1518             (
1519             SAVE => sub
1520             {
1521 0     0     my (@name_values) = @_ ;
1522            
1523 0 0         if(scalar(@_) % 2)
1524             {
1525 0           my ($package, $file_name, $line) = caller() ;
1526            
1527 0           $self->{INTERACTION}{DIE}->
1528             (
1529             $self,
1530             "$self->{NAME}: eval-side persistence handler got unexpected number of arguments "
1531             . "at '$file_name:$line'!"
1532             )   ;
1533             }
1534            
1535 0           while(my ($variable_name, $value) = splice(@name_values, 0, 2))
1536             {
1537 0           $handler_sub_validators{SAVE}->($self, $variable_name, $value) ;
1538            
1539 0           $self->{PERSISTENT_VARIABLES_FOR_EVAL_SIDE}{$category}{$variable_name} = $value ;
1540             }
1541             },
1542            
1543             GET  => sub
1544             {
1545 0     0     my @values ;
1546            
1547 0           for my $variable_name (@_)
1548             {
1549 0           $handler_sub_validators{GET}->($self, $variable_name) ;
1550            
1551 0           push @values, $self->{PERSISTENT_VARIABLES_FOR_EVAL_SIDE}{$category}{$variable_name} ;
1552             }
1553            
1554 0 0         return wantarray ? @values : $values[0] ;
1555             },
1556            
1557 0           ) ;
1558            
1559 0           for my $handler_type ('SAVE', 'GET')
1560             {
1561 0 0         if(exists $options->{EVAL_SIDE_PERSISTENT_VARIABLES}{$handler_type})
1562             {
1563 0 0 0       if
      0        
      0        
1564             (
1565             exists $options->{EVAL_SIDE_PERSISTENT_VARIABLES}{$handler_type}{VALIDATOR}
1566             && 'CODE' eq ref $options->{EVAL_SIDE_PERSISTENT_VARIABLES}{$handler_type}{VALIDATOR}
1567             && $EMPTY_STRING eq ref $options->{EVAL_SIDE_PERSISTENT_VARIABLES}{$handler_type}{NAME}
1568             && $EMPTY_STRING ne $options->{EVAL_SIDE_PERSISTENT_VARIABLES}{$handler_type}{NAME}
1569             )
1570             {
1571 0           $handler_sub_validators{$handler_type} = $options->{EVAL_SIDE_PERSISTENT_VARIABLES}{$handler_type}{VALIDATOR} ;
1572            
1573 0           reinstall_sub({
1574             code => $handler_subs{$handler_type},
1575             into => $self->{CURRENT_RUNNING_PACKAGE},
1576             as => $options->{EVAL_SIDE_PERSISTENT_VARIABLES}{$handler_type}{NAME}
1577             }) ;
1578             }
1579             else
1580             {
1581 0           $options->{INTERACTION}{DIE}->
1582             (
1583             $self,
1584             "$self->{NAME}: 'EVAL_SIDE_PERSISTENT_VARIABLES' invalid definition "
1585             . "at '$options->{FILE}:$options->{LINE}'!"
1586             )  ;
1587             }
1588             }
1589             else
1590             {
1591 0           $options->{INTERACTION}{DIE}->
1592             (
1593             $self,
1594             "$self->{NAME}: 'EVAL_SIDE_PERSISTENT_VARIABLES' missing handler definition "
1595             . "at '$options->{FILE}:$options->{LINE}'!"
1596             )  ;
1597             }
1598             }
1599            
1600 0 0         if($options->{EVAL_SIDE_PERSISTENT_VARIABLES}{SAVE}{NAME} eq $options->{EVAL_SIDE_PERSISTENT_VARIABLES}{GET}{NAME})
1601             {
1602 0           $options->{INTERACTION}{DIE}->
1603             (
1604             $self,
1605             "$self->{NAME}: invalid definition, eval-side persistence handlers have the same name "
1606             . "at '$options->{FILE}:$options->{LINE}'!"
1607             )  ;
1608             }
1609             }
1610             else
1611             {
1612 0           $options->{INTERACTION}{DIE}->($self, "$self->{NAME}: 'EVAL_SIDE_PERSISTENT_VARIABLES' isn't a hash reference at '$options->{FILE}:$options->{LINE}'!") ;
1613             }
1614            
1615 0           return(1) ;
1616             }
1617              
1618             #-------------------------------------------------------------------------------
1619              
1620             sub RemoveEvalSidePersistenceHandlers
1621             {
1622              
1623             =head2 [p] RemoveEvalSidePersistenceHandlers
1624            
1625             Removes I<eval-side> persistent variable handlers. Used after calling C<eval> so the
1626             next C<eval> can not access I<eval-side> persistent variables without being allowed to do so.
1627            
1628             =cut
1629              
1630 0     0 1   my ($self, $options) = @_ ;
1631              
1632 0           for my $handler_type ('SAVE', 'GET')
1633             {
1634             reinstall_sub({
1635             code => sub
1636             {
1637 0     0     $options->{INTERACTION}{DIE}->
1638             (
1639             $self,
1640             "$self->{NAME}: No Persistence allowed on eval-side in package '$self->{CURRENT_RUNNING_PACKAGE}'!\n"
1641             ) ;
1642             },
1643            
1644 0           into => $self->{CURRENT_RUNNING_PACKAGE},
1645             as => $options->{EVAL_SIDE_PERSISTENT_VARIABLES}{$handler_type}{NAME}
1646             }) ;
1647             }
1648              
1649 0           return(1) ;
1650             }
1651              
1652             #-------------------------------------------------------------------------------
1653              
1654             1 ;
1655              
1656             =head1 BUGS AND LIMITATIONS
1657            
1658             I have reported a very strange error when B<Safe> and B<Carp> are used together.
1659             L<http://rt.cpan.org/Ticket/Display.html?id=31090>. The error can be reproduced
1660             without using B<Eval::Context>.
1661            
1662             =head1 AUTHOR
1663            
1664             Khemir Nadim ibn Hamouda
1665             CPAN ID: NKH
1666             mailto:nadim@khemir.net
1667            
1668             =head1 LICENSE AND COPYRIGHT
1669            
1670             This program is free software; you can redistribute
1671             it and/or modify it under the same terms as Perl itself.
1672            
1673             =head1 SUPPORT
1674            
1675             You can find documentation for this module with the perldoc command.
1676            
1677             perldoc Eval::Context
1678            
1679             You can also look for information at:
1680            
1681             =over 4
1682            
1683             =item * AnnoCPAN: Annotated CPAN documentation
1684            
1685             L<http://annocpan.org/dist/Eval-Context>
1686            
1687             =item * RT: CPAN's request tracker
1688            
1689             Please report any bugs or feature requests to L <bug-eval-context@rt.cpan.org>.
1690            
1691             We will be notified, and then you'll automatically be notified of progress on
1692             your bug as we make changes.
1693            
1694             =item * Search CPAN
1695            
1696             L<http://search.cpan.org/dist/Eval-Context>
1697            
1698             =back
1699            
1700             =cut
1701