lib/DB/Commands.pm untested

filter: Statementstmt 0.0% 0 / 575 Branchbran 0.0% 0 / 282 Conditioncond 0.0% 0 / 133 MC/DCmcdc 0.0% 0 / 78 Subroutinesub 0.0% 0 / 51 Podpod 0.0% 0 / 39 totaltotal 0.0% 0 / 1158 CC 141 SCAR 53.6
CC
141
Cov
0%
cmd_variables
930.0
cmd_breakpoint
240.0
list_source
210.0
CRAP 213.2
1 package DB::Commands;
2  
3 use strict;
4 use warnings;
5  
6 #To work with color
7 my $hl;
8 my $lm;
9 my $is_exists = `ldconfig -p | grep -c libsource-highlight`;
10 chomp($is_exists);
11  
12 sub highlighting {
13 require Syntax::SourceHighlight;
14  
15 $hl = Syntax::SourceHighlight->new('esc.outlang');
16 $lm = Syntax::SourceHighlight::LangMap->new();
17 $hl->setStyleFile('esc256.style');
18  
19 return 1;
20 }
21  
22 our $lines_before = 10;
23 our $lines_after = 20;
24 my $highlight = $is_exists && !$ENV{ DEBUGGER_NO_COLOR } ? highlighting() : 0;
25  
26 sub DB::say;
27 sub import {
28 my $pkg = shift;
29 my $call_pkg = caller;
30  
31 no strict "refs";
32 *{"$call_pkg\::$_"} = \&{"$pkg\::$_"} foreach @_;
33 }
34  
35  
36  
37 sub set_command {
38 my( $name, $handler, $alias ) = @_;
39  
40 $DB::commands->{ $name } = $handler;
41 $DB::commands->{ $alias } = $handler if length $alias;
42 }
43  
44  
45  
46 sub get_command {
47 my( $name ) = @_;
48  
49 return $DB::commands->{ $name };
50 }
51  
52  
53  
54 # Purpose of this sub is to display error if it occurs OR call supplied CODE
55 # Then return command to continue interaction with user
56 sub stay(&) {
57 my $stay = DB::state( 'stay' ) // get_command 'interact';
58 my $code = shift;
59 return sub{
60 $code->( @_ ), return $stay
61 unless ref $_[0] eq 'DB::Error';
62  
63 DB::say DB::_c( "ERROR", "1;31" ) .": $_[0]";
64 return $stay;
65 }
66 }
67  
68  
69  
70 sub interact {
71 my $str = get_command( 'next_command' )->() // exit;
72 # DB::say DB::_c("Your input: ") .$str;
73  
74 while(1) {
75 my $result = run( $str );
76 return unless defined $result; # Stop interaction if we got undef
77 return $result if ref $result; # Restart processing based on command result
78  
79 # Continue interaction if we got TRUE value
80 return get_command 'interact' unless $result == 0;
81  
82 # $result == 0: Command not found, so
83 # Run default command for not recognised string
84  
85 $str =~ m/^\s/?
86 ($str = "mdump $str"):
87 ($str = "vars $str");
88 }
89 }
90  
91  
92  
93 sub run {
94 my $str = shift // return;
95  
96 my( $cmd, $args_str ) = $str =~ m/^\s*([\w.]+)(?:\s+(.*?)\s*)?$/;
97 $args_str //= '';
98  
99  
100 unless( $cmd && exists $DB::commands->{ $cmd } ) {
101 # print $DB::OUT "No such command: '$str'\n" if DB::state( 'ddd' );
102 return 0;
103 }
104  
105 # The command should return defined value to keep interaction
106 # print $DB::OUT "Start to run '$cmd' command\n" if DB::state( 'ddd' );
107 my $result = eval { $DB::commands->{ $cmd }( $args_str ) };
108 # print $DB::OUT "Command '$cmd' done\n" if DB::state( 'ddd' );
109 do{ DB::say "'$cmd' " .DB::_c( "command died", '1;31' ). ": $@"; return -1; } if $@;
110  
111 return $result;
112 }
113  
114  
115  
116 sub _dd {
117 require Data::Dump;
118 Data::Dump::pp( @_ );
119 }
120  
121  
122  
123 ## Debugger commands
124 # filename/number; delimeter ':' ; linenumber
125 my $file_line = qr/(?:(.+):)?(\d+|\.)/;
126  
127 # Evaluate data in user's context and display it in various format
128 sub cmd_mdump {
129 my( $expr ) = @_;
130  
131 return [ stay {
132 DB::say DB::_c( "Evaluation result: ", 32 ) if DB::state( 'ddd' ) &1;
133 DB::say $_ for map{ DB::dumper( $_ ) } @{ $_[0] };
134 }
135 ,$expr
136 ];
137 }
138  
139  
140  
141 sub cmd_print_eval {
142 my( $expr ) = @_;
143  
144 return [ stay {
145 DB::say DB::_c( "Evaluation result: ", 32 ) if DB::state( 'ddd' ) &1;
146 DB::say join "\n", DB::vis_undef( @{ $_[0] } );
147 }
148 ,$expr
149 ];
150 }
151  
152  
153  
154 sub cmd_dump_eval {
155 my( $expr ) = @_;
156  
157 return [ stay {
158 DB::say DB::_c( "Dump result: ", 32 ) if DB::state( 'ddd' ) &1;
159 DB::say _dd( @{ $_[0] } );
160 }
161 ,length $expr ? $expr : DB::state( 'last_eval' ) // ''
162 ];
163 }
164  
165  
166  
167 sub cmd_ddp {
168 my( $expr ) = @_;
169 require DDP;
170  
171 return [ stay {
172 DB::say DDP::np( @{ $_[0] } );
173 }
174 ,length $expr ? $expr : DB::state( 'last_eval' ) // ''
175 ];
176 }
177  
178  
179  
180 sub cmd_peek {
181 my( $expr ) = @_;
182 require Devel::Peek;
183  
184 return [ stay {
185 Devel::Peek::Dump( @{ $_[0] } );
186 }
187 ,length $expr ? $expr : DB::state( 'last_eval' ) // ''
188 ];
189 }
190  
191  
192  
193 # Main set of commands
194 sub cmd_quit {
195 DB::state( single => 0 );
196 exit;
197 }
198  
199  
200  
201 sub cmd_step {
202 if( shift =~ m/^(\d+)$/ ) {
203 my $steps_left = $1;
204 DB::state( 'step.steps_left' => \$steps_left );
205  
206 my $handler; $handler = sub {
207 return 0 if --$steps_left;
208  
209 DB::state( 'step.steps_left' => undef );
210 DB::unsubscribe( stop => $handler );
211  
212 # Is not required: single step is based on fact that $DB::single is TRUE
213 # DB::state( single => 1 );
214 return 1;
215 };
216  
217 DB::on( stop => $handler );
218 }
219  
220 DB::state( single => 1 );
221 return;
222 }
223  
224  
225  
226 sub cmd_stepover {
227 my( $steps_left ) = shift =~ m/^(\d+)$/;
228 $steps_left //= 1;
229 DB::state( 'stepover.steps_left' => \$steps_left );
230  
231  
232 ## Count frames
233 my $frames_left = 0;
234 my $increase = sub{
235 DB::state( 'stepover.frames_left' => \$frames_left ) ,DB::state( single => 0 )
236 if $frames_left == 0;
237  
238 $frames_left++;
239 return;
240 };
241 my $decrease = sub{
242 $frames_left--;
243 DB::state( 'stepover.frames_left' => undef ) ,DB::state( single => 2 )
244 if $frames_left == 0;
245  
246 return;
247 };
248 my $goto = sub{
249 # .at_frame has DB::DB frame (breakpoint line), DB::goto has no DB::DB frame, so +1
250 $increase->() if DB::state( 'stepover.at_frame' ) == 1+ DB::fcount;
251  
252 return;
253 };
254  
255  
256 my $finish; $finish = sub {
257 # use and require silently add frame into callstack
258 # So we check here that we stopped at same or upper level
259 # TODO? Should we check $is_require flag to ensure (eval)?
260 # Use of uninitialized value in numeric lt (<) at ...
261 return if DB::state( 'stepover.at_frame' ) < DB::fcount;
262  
263 return 0 if --$steps_left;
264  
265 DB::state( 'stepover.at_frame' => undef );
266 DB::state( 'stepover.steps_left' => undef );
267 DB::unsubscribe( call => $increase );
268 DB::unsubscribe( return => $decrease );
269 DB::unsubscribe( goto => $goto );
270 DB::unsubscribe( stop => $finish );
271  
272 # Is not required: step over is based on fact that $DB::single is TRUE
273 # DB::state( single => 2 );
274 return 1;
275 };
276  
277 DB::state( 'stepover.at_frame' => DB::fcount );
278 DB::on( call => $increase );
279 DB::on( return => $decrease );
280 DB::on( goto => $goto );
281 DB::on( stop => $finish );
282  
283 DB::state( single => 2 );
284 return;
285 }
286  
287  
288  
289 sub cmd_stepout {
290 my( $frames_left, $sharp ) = shift =~ m/^(\d+)(\^)?$/;
291  
292 if( $sharp ) {
293 my $frames;
294 1 while caller( 12 + $frames++ );
295 $frames_left = $frames -$frames_left +1;
296  
297 return -2 if $frames_left <= 0; # Do nothing for unexisting frame
298 }
299  
300 my $leave_chain = defined $frames_left;
301 $frames_left //= 1;
302  
303 DB::state( 'stepout.frames_left' => \$frames_left );
304  
305  
306 ## Count frames
307 my $increase = sub{
308 DB::state( single => 0 ) if $leave_chain && !$frames_left;
309 $frames_left++;
310 return
311 };
312 my $decrease = sub{
313 return if --$frames_left;
314  
315 # When we return from sub we do not know what would be next:
316 # 1. We stopped at outer frame
317 # 2. We stopped at another call
318 DB::state( single => 1 );
319 return;
320 };
321 my $finish; $finish = sub {
322 DB::state( 'stepout.frames_left' => undef );
323 DB::unsubscribe( call => $increase );
324 DB::unsubscribe( return => $decrease );
325 DB::unsubscribe( stop => $finish );
326 # TODO: IT: make test to that checks no subscribers are left after command is finished
327  
328 return 1;
329 };
330  
331 DB::on( call => $increase );
332 DB::on( return => $decrease );
333 DB::on( stop => $finish );
334  
335  
336 DB::state( single => 0 );
337 return;
338 }
339  
340  
341  
342 sub cmd_continue {
343 if( length $_[0] ) {
344 get_command( 'breakpoint' )->( "$_[0]!" );
345 }
346  
347 DB::state( single => 0 );
348 return;
349 }
350  
351  
352  
353 sub breakpoint_handler {
354 my( $trap, $f, $l ) = @_;
355  
356 if( $trap->{ once } ) {
357 delete $trap->{ once };
358 delete DB::traps( $f )->{ $l } if !keys %$trap;
359 return 1;
360 }
361  
362 return 0 if $trap->{ disabled } || !exists $trap->{ condition };
363  
364 # Evaluate condition at user's context and just return obtained result
365 return [ sub{
366 return 0 unless my $result = shift->[0];
367  
368  
369 DB::say "Stopped by breakpoint condition: "
370 .$trap->{ condition } .' --> ' .DB::dumper $result
371 if DB::state( 'verbose.commands' );
372  
373 return 1;
374 }
375 ,$trap->{ condition }
376 ];
377 }
378  
379  
380  
381 sub breakpoint_on_call_handler {
382 my( $subname ) = @_;
383  
384 my $traps = DB::state( 'breakpoint.subs' );
385  
386 my $by;
387 if(
388 $traps->{ $subname } # not disabled (value is TRUE)
389  
390 || grep{ # OR
391 $by = $_;
392 $traps->{ $_ } # not disabled
393 && # &&
394 $subname =~ m/$_/ # current sub match
395 } keys %$traps
396 ) {
397 DB::say "Stopped by subroutine condition: " .$by
398 if DB::state( 'verbose.commands' );
399 DB::state( single => 1 ); # Stop on next OP
400 }
401  
402 return;
403 }
404  
405  
406  
407 sub list_breakpoints {
408 my( $file ) = @_;
409 my $list = [];
410  
411  
412 # First display traps in the current file
413 DB::say "Breakpoints:";
414 for my $source ( $file, grep { $_ ne $file } keys %$DB::_tfiles ) {
415 my $traps = DB::traps( $source );
416 next unless keys %$traps;
417  
418 push @$list, $source;
419 DB::say $#$list ." $source";
420  
421 for( sort{ $a <=> $b } keys %$traps ) {
422 DB::say sprintf " %-3d%s %s"
423 , $_
424 , exists $traps->{ $_ }{ once } ? '!'
425 : exists $traps->{ $_ }{ disabled }? '-' : ':'
426 , $traps->{ $_ }{ condition } // ''; # One time trap has no condition
427  
428 DB::say sprintf " %-3d%s %s", $_, 'a', $traps->{ $_ }{ action }
429 if exists $traps->{ $_ }{ action };
430  
431  
432 DB::warn "The breakpoint at $_ is not breakable"
433 if $traps->{ $_ } == 0;
434 }
435 }
436 DB::state( 'files.list', $list );
437  
438  
439 DB::say "Stop on subs:";
440 my $traps = DB::state( 'breakpoint.subs' );
441  
442 DB::say ' ' .($traps->{ $_ } ? ' ' : '-') ."$_"
443 for keys %$traps;
444  
445 DB::say '';
446  
447 return 1;
448 }
449  
450  
451  
452 sub cmd_breakpoint {
453 my( $sign, $f, $l, $subname, $condition, $once ) =
454 shift =~ m/^([-+])?(?:${file_line}|([\w:\$\^\|]+|&\d*))(?:\s+(.+?))??\s*(!)?$/;
455  
456 if( length $subname ) {
457 if( $subname =~ m/^&(\d*)$/ ) {
458 my $frame = defined $1 ? $1 : DB::state( 'list.level' )//0;
459 $subname = DB::sub_name( sub_at_frame( $frame ) );
460 }
461  
462 return -1 unless $subname; # main:: is not subroutine
463  
464 ## Set breakpoint
465 my $bs = DB::state( 'breakpoint.subs' );
466 unless( $bs ) {
467 $bs = {};
468 DB::on( call => \&breakpoint_on_call_handler );
469 DB::on( goto => \&breakpoint_on_call_handler );
470 }
471 $bs->{ $subname } = $sign && $sign eq '-' ? 0 : 1;
472 DB::state( 'breakpoint.subs' => $bs );
473  
474 DB::say "$subname is added to breakpoint list"
475 if DB::state( 'verbose.commands' );
476  
477 return 1;
478 }
479  
480  
481 $f = current_file( $f );
482 return list_breakpoints( $f ) unless defined $l;
483  
484 # FIX: Get line at current level
485 $l = DB::state( 'line' ) if $l eq '.';
486  
487 unless( DB::can_break( $f, $l ) ) {
488 DB::warn( "$f:$l -- This line is not breakable" );
489 # Set breakpoint in any case. This is usefull when you edit file
490 # and want to add traps to those new lines
491 # return -1;
492 }
493  
494  
495 ## Set breakpoint
496 my $trap = \DB::traps( $f )->{ $l };
497  
498 # TODO: Move trap from/into $traps into/from $disabled_traps
499 # This will allow us to not trigger DB::DB if trap is disabled
500 $$trap->{ disabled } = 1 if $sign && $sign eq '-';
501 delete $$trap->{ disabled } if $sign && $sign eq '+';
502  
503 if( $once ) { # One time breakpoint has not condition
504 $$trap->{ once } = 1;
505 }
506 else {
507 $$trap->{ condition } = $condition if defined $condition;
508 $$trap->{ condition } //= 1; # Trigger always by default
509 };
510  
511  
512 return 1;
513 }
514  
515  
516  
517 sub action_handler {
518 my( $trap, $f, $l ) = @_;
519  
520 defined $trap->{ action } or return;
521  
522 DB::state( stay => 0 ); # Prevent command from interaction with user
523 my $result = run( $trap->{ action } );
524 DB::state( stay => undef );
525 return $result unless defined $result && $result == 0;
526  
527 # Evaluate action at user's context and return zero to not stop execution
528 return [ sub{ 0 }, $trap->{ action } ];
529 }
530  
531  
532  
533 sub cmd_action {
534 my( $f, $l, $expr ) = shift =~ m/^${file_line}(?:\s+(.*))$/;
535 return unless length $expr;
536  
537 $f = current_file( $f );
538 $l = DB::state( 'line' ) if $l eq '.';
539  
540  
541 unless( DB::can_break( $f, $l ) ) {
542 DB::warn( "$f:$l -- This line is not breakable" );
543 # Set action in any case. This is usefull when you edit file
544 # and want to add traps to those new lines
545 # return -1;
546 }
547  
548  
549 ## Set action
550 my $trap = \DB::traps( $f )->{ $l };
551  
552 $$trap->{ action } = $expr;
553  
554  
555 return 1;
556 }
557  
558  
559  
560 sub current_file {
561 return DB::state( 'files.current' ) // DB::state( 'file' )
562 unless @_;
563  
564 my( $file ) = @_;
565 $file //= DB::state( 'files.current' ) // DB::state( 'file' );
566  
567 my $files = DB::state( 'files.list' );
568 $file = $files->[ $file ]
569 if $file =~ m/^(\d+)$/ && exists $files->[ $file ];
570  
571 # TODO? warn if file is not loaded into project
572  
573 DB::state( 'files.current', $file );
574  
575 return $file;
576  
577 }
578  
579  
580  
581 sub cmd_files {
582 my( $args, $expr ) = @_;
583  
584 # Set chosen file as current:
585 if( $args ne '' && $args =~ /^(\d+)$/ ) {
586 DB::say current_file( $args );
587 return 1;
588 }
589  
590 # List available files
591 my $cmd_f = [];
592 my $file_no = 0;
593 my @not_loaded = map{ "Not loaded: $_" } grep{ !defined $INC{ $_ } } keys %INC;
594 for( sort $0, @not_loaded, grep{ defined } values %INC, DB::sources() ) {
595 # for( sort $0, keys %$expr ) {
596 if( /(?:$args)/ ) {
597 push @$cmd_f, $_;
598 DB::say $file_no++ ." $_";
599 }
600 }
601  
602  
603 DB::state( 'files.list', $cmd_f );
604 1;
605 }
606  
607  
608  
609 sub call_points {
610 my( $file, $frames ) = @_;
611 $frames //= DB::frames();
612  
613 my $lvl = 0;
614 my $lines = {};
615 for( @$frames ) {
616 $lines->{ $_->[ 3 ] } //= $lvl if $_->[ 2 ] eq $file;
617 $lvl++;
618 }
619  
620 return $lines;
621 }
622  
623  
624  
625 sub list_source {
626 my( $file, $from, $to ) = @_;
627  
628 # Fix window boundaries
629 my $source = DB::source( $file );
630 $from = 0 if $from < 0; # TODO: testcase; 0 exists if -d
631 $to = $#$source if $to > $#$source; # TODO: testcase
632  
633 # The place where to display *cursor*: '>>'
634 my $cursor_at = call_points( $file );
635  
636  
637 my $traps = DB::traps( $file );
638 for my $line ( $from..$to ) {
639 next unless exists $source->[ $line ];
640  
641 my $info = '';
642 # Print flags
643 if( exists $traps->{ $line } ) {
644 $info .= exists $traps->{ $line }{ action } ? 'a' : ' ';
645 $info .= exists $traps->{ $line }{ once } ? '!'
646 : exists $traps->{ $line }{ disabled }? '-'
647 : exists $traps->{ $line }{ condition }? 'b' : ' ';
648 }
649 else {
650 $info .= ' ';
651 }
652  
653  
654 # Print *breakable* and *cursor* marks
655 if( defined( my $level = $cursor_at->{ $line } ) ) {
656 if( $level ) {
657 if( $level < 10 ) {
658 $info .= DB::_c( "$level>", '2;33' );
659 }
660 else {
661 $info .= DB::_c( "*>", '2;93' );
662 }
663 }
664 else {
665 $info .= DB::_c( ">>", '2;93' );
666 }
667 }
668 else {
669 $info .= DB::can_break( $file, $line ) ? ' x' : ' ';
670 }
671  
672  
673 # Print source line number
674 $info .= "$line:";
675  
676  
677 # Print source line
678 (my $src = $source->[ $line ]) =~ s/^\t/ /g;
679 $src = "$info $src";
680 $src =~ s/\s+$//; # Remove whitespaces at EOL
681  
682 $src = $highlight ? $hl->highlightString( $src, $lm->getMappedFileName('perl') ) : $src;
683  
684 DB::say $src;
685 }
686  
687 DB::say; # WORKAROUND: Data::Section::Simple: last line always has EOL
688 }
689  
690  
691  
692 sub list_file {
693 my( $stack, $file, $from, $to ) = @_;
694  
695 if( !defined $stack && !defined $from ) { # case: l
696 # Just list source at current position
697 $from = DB::state( 'list.line' );
698 $from = defined $from ? $from +$lines_before : DB::state( 'line' );
699 }
700 elsif( $stack && !defined $file || $from eq '.' ) {
701 if( $stack && (my( $sub ) = $stack =~ m/^-(\D.*)$/) ) { # case: l -sub
702 my $frames = DB::frames();
703  
704 $from = 0;
705 while( @$frames ) {
706 last if $frames->[0][4] =~ m/$sub/;
707 shift @$frames;
708 $from++;
709 }
710  
711 # Return if not found requested sub at stack
712 @$frames or return 1;
713  
714 DB::say( "Found at frame -$from" );
715 }
716  
717 if( !defined $from ) { # case: l -
718 $from = DB::state( 'list.level' ) +1;
719 DB::say "Level: $from" if $from > 9;
720 }
721  
722 $from = DB::state( 'list.level' ) // 0 if $from eq '.'; # case: l .
723 DB::state( 'list.level', $from );
724  
725 my $frames = DB::frames();
726 return -2 if $from +1 > @$frames;
727  
728 ( $file, $from ) = @{ $frames->[ $from ] }[ 2, 3 ];
729 $to = $from +$lines_before;
730 $from -= $lines_after;
731 }
732 elsif( $from eq '0' ) { # case: l 0
733 DB::state( 'files.current', undef );
734 DB::state( 'list.level', undef );
735 $file = DB::state( 'file' );
736 $from = DB::state( 'line' );
737 }
738 else { # case: l f/ile:10
739 # file:line are provided we should flush { list.level } (See commit)
740 DB::state( 'list.level', undef );
741 }
742  
743 $file = current_file( $file );
744 if( !defined $to ) {
745 $to = $from +$lines_after;
746 $from -= $lines_before;
747 }
748  
749 DB::say '', $file; # Print current file unconditionally
750 list_source( $file, $from, $to );
751  
752 DB::state( 'list.line', $to +1 ); # continue listing from next line
753 return 1;
754 }
755  
756  
757  
758 sub list_sub {
759 my( $deparse, $eval, $subname ) = @_;
760 return -2 unless defined $subname;
761  
762 # 1. List sub by code ref in the variable
763 $eval && return [ stay {
764 list_sub( $deparse, undef, $_[0][0] );
765 }
766 ,'$' .$subname
767 ];
768  
769  
770  
771 $subname = DB::state( 'package' ) ."::$subname"
772 if !ref $subname && $subname !~ m/::/;
773  
774 # 2. Deparse sub
775 if( $deparse ) {
776 no strict 'refs';
777 DB::say DB::sub_name( $subname ) .' '
778 .DB::deparse ref $subname ? $subname : \&{ $subname };
779  
780 DB::say; # WORKAROUND: Data::Section::Simple: last line always has EOL
781 return 1;
782 }
783  
784  
785 # 3. List sub from source
786 my $location = DB::location( $subname );
787 DB::warn "Subroutine $subname is not known"
788 ,return -1 unless defined $location;
789  
790 # The location format is 'file:from-to'
791 $location =~ m/^(.*):(\d+)-(\d+)$/;
792 list_source( $1, $2, $3 );
793  
794  
795 return 1;
796 }
797  
798  
799  
800 sub sub_at_frame {
801 my( $frame ) = @_;
802 $frame //= DB::state( 'list.level' );
803 $frame += 2;
804  
805 my $frames = DB::frames( $frame );
806 return if @$frames < $frame; # We have less frames then requested
807  
808 return $frames->[-1][4];
809 }
810  
811  
812  
813 sub cmd_list {
814 my( $args ) = @_;
815  
816 my @args = $args =~ m/^(&?)(\$?)([A-Za-z].*)$/;
817 return list_sub( @args ) if @args;
818  
819 @args = $args =~ m/^&(\d+)?$/;
820 return list_sub( undef, undef, sub_at_frame( @args ) ) if @args;
821  
822 # stack mark '-'; optional subname; fileline; range '-number'
823 @args = $args =~ m/^(-(?:\D.*)?)?${file_line}?(?:-(\d+))?$/;
824 return list_file( @args );
825 }
826  
827  
828  
829 my $trace_format = {()
830 ,sub =>
831 '"$fn $package - $subname"'
832 ,simple =>
833 '"$fn $package - $file:$line - $subname"'
834 ,oneline =>
835 '"\n$fn $context $subname$args <-- $file:$line"'
836 ,multiline =>
837 '"\n$fn $subname\n $context $args\n <-- $file:$line"'
838 };
839 sub cmd_stack_trace {
840 my( $one, $count, $format ) = shift =~ m/^(-?)(\d+)(?:\s+(\w*))?$/;
841 $format //= 'oneline'; # TODO: Get default format from options
842  
843 # TODO: Clarify code
844 my $frames = DB::frames( defined $count? $count +($one?1:0) : () );
845 my $fn = 0; # frame number
846 if( $one ) { # At this case $count means target frame
847 return get_command 'interact' unless $count <= @$frames;
848 $fn = $count;
849 $frames = [ $frames->[ $fn ] ];
850 }
851  
852 for my $frame ( @$frames ) {
853 my( $package, $file, $line, $subname ) = @$frame[1..4];
854 $fn = 0 if $subname eq 'DB::DB';
855 my $args = $frame->[5] ? $frame->[0] : '';
856 my $context = $frame->[6]? '@' : defined $frame->[6]? '$' : ';';
857  
858 if( $args ) {
859 $args = join ', ', map{ defined $_ ? $_ : 'undef' } @$args;
860 $args = "($args)";
861 }
862  
863 DB::say eval $trace_format->{ $format };
864 DB::say $@ if $@;
865 $fn++;
866 }
867  
868 return get_command 'interact';
869 }
870  
871  
872  
873 sub cmd_debug_expr {
874 my( $expr ) = @_;
875  
876 $expr =~ s/(?<!\\);/;\n/;
877 $expr =~ s/\\;/;/;
878  
879 return [ stay {
880 DB::say "Debug result: @{ $_[0] }";
881 }
882 ,"\$^D |= (1<<30);\$DB::single= 1;\n" .$expr
883 ]
884 }
885  
886  
887  
888 sub get_stash {
889 require 'Package/Stash.pm'; # BUG? spoils DB:: by emacs, dbline
890  
891 my $pkg = DB::state( 'package' );
892 my $stash = Package::Stash->new( $pkg )->get_all_symbols();
893  
894 return $stash, $pkg;
895 }
896  
897  
898  
899 sub get_variables {
900 require 'PadWalker.pm';
901 # my @subs;
902 # my $package_name = caller( DB::state( 'level.frame' ) )[0];
903 # foreach $name ( keys %{$package_name .'::'} ) {
904 # push @subs, $name;
905 # }
906  
907 my $my = PadWalker::peek_my ( DB::state( 'level.frame' ) );
908 my $our = PadWalker::peek_our( DB::state( 'level.frame' ) );
909  
910  
911  
912 return $my, $our;
913 }
914  
915  
916  
917 sub cmd_variables {
918 my( $level, $flags, $expr ) =
919 (' '.shift) =~ m/^(?:\s+-(\d+))?(?:\s+([amogucs]+))?(?:\s+(.*))?$/;
920  
921 $flags //= '';
922  
923 my $type = 0;
924 for( split '', $flags ) {
925 $type |= ~0 if /^a|all$/;
926 $type |= 1 if /^m|my$/;
927 $type |= 2 if /^o|our$/;
928 $type |= 4 if /^g|global$/;
929 $type |= 8 if /^u|used$/;
930 $type |= 16 if /^c|closured$/;
931 $type |= 24 if /^s|sub$/; #u+c
932 }
933 $level //= DB::state( 'list.level' ) // 0;
934 $type ||= DB::state( 'vars.type' ) || 3 unless $expr;
935  
936 my( $frames, $evals ) = ( 0, 0 );
937 { # Count debugger and eval frames
938 my @frame;
939 while( @frame = caller( $frames++ ) and $frame[3] ne 'DB::DB' ) {
940 $evals++ if $frame[3] eq '(eval)';
941 }
942 while( @frame = caller( $frames++ ) and $level-- > 0 ) {
943 $evals++ if $frame[3] eq '(eval)';
944 }
945 $frames--;
946 }
947  
948  
949  
950 #FIX: When we debug debugger we can not 'go <line>' we always stops at
951 #require at third line at PadWalker.pm. Debug who set $DB::state = 1
952 require 'PadWalker.pm';
953  
954 my $my = PadWalker::peek_my ( $frames -$evals );
955 my $our = PadWalker::peek_our( $frames -$evals );
956  
957 if( $type & 1 ) {
958 # TODO: for terminals which support color show
959 # 1. not used variables as grey
960 # 2. closed over variables as green or bold
961 DB::say "MY:", join( ', ', sort keys %$my );
962 }
963  
964 if( $type & 2 ) {
965 DB::say "OUR:", join( ', ', sort keys %$our );
966 }
967  
968 if( $type & 4 ) {
969 require 'Package/Stash.pm'; # BUG? spoils DB:: by emacs, dbline
970  
971 my $pkg = DB::state( 'package' );
972 my $stash = Package::Stash->new( $pkg )->get_all_symbols();
973 # Show only user defined variables
974 # TODO? implement verbose flag
975 # Probably, as MST adviced, we can capture the contents of 'main'
976 # *before* you evaluate anything
977 if( $pkg eq 'main' ) {
978 for( keys %$stash ) {
979 delete $stash->{ $_ } if /::$/;
980 delete $stash->{ $_ } if /^_</;
981 delete $stash->{ $_ } if /^[\x00-\x1f]/; #Remove $^ variables
982 }
983  
984 delete @$stash{ qw# STDERR stderr STDIN stdin STDOUT stdout # };
985 delete @$stash{ qw# BEGIN INIT CHECK END # };
986 delete @$stash{ qw# SIG INC F ] ENV ; > < ) ( $ " _ # }; # a b
987 delete @$stash{ qw# - + ` & ' #, 0..99 };
988 # BUG? warning still exists despite on explicit escaping of ','
989 delete @$stash{ ',', qw# ARGV ARGVOUT . / \\ | # };
990 delete @$stash{ qw# % - : = ^ ~ # };
991 delete @$stash{ qw# ! @ ? # };
992 }
993 delete $stash->{ sub } if $pkg eq 'DB';
994  
995 my @globals = ();
996 my %sigil = ( SCALAR => '$', ARRAY => '@', HASH => '%' );
997 for my $key ( keys %$stash ) {
998 my $glob = $stash->{ $key };
999 for my $type ( keys %sigil ) {
1000 next unless defined *{ $glob }{ $type };
1001 next if $type eq 'SCALAR' && !defined $$glob;
1002 next if $key =~ /::/;
1003 push @globals, $sigil{ $type } .$key;
1004 }
1005 }
1006  
1007 DB::say "GLOBAL:", join( ', ', sort @globals );
1008 }
1009  
1010 if( $type & 8 ) {
1011 DB::say "USED:";
1012  
1013 # First element starts at -1 subscript
1014 # FIX: When debug debugger and we step over this statement
1015 # the $sub contain reference to &vars instead of name of last
1016 # client's sub
1017 my $sub = DB::frames( $level +2 )->[-1][4];
1018 if( !defined $sub ) {
1019 # TODO: Mojolicious::__ANON__[/home/feelsafe/perl_lib/lib/perl5/Mojolicious.pm:119]
1020 # convert this to subroutine refs
1021 DB::say "Not in a sub: $sub";
1022 }
1023 else {
1024 $sub = \&$sub;
1025 DB::say join( ', ', sort keys %{ PadWalker::peek_sub( $sub ) } );
1026 }
1027 }
1028  
1029 if( $type & 16 ) {
1030 DB::say "CLOSED OVER:";
1031  
1032 # First elements starts at -1 subscript
1033 my $sub = DB::frames( $level +2 )->[-1][4];
1034 if( !defined $sub ) {
1035 DB::say "Not in a sub: $sub";
1036 }
1037 else {
1038 $sub = \&$sub;
1039 DB::say join( ', ', sort keys %{ (PadWalker::closed_over( $sub ))[0] } );
1040 }
1041 }
1042  
1043 if( $expr ) {
1044 (my $vars, $expr) = split ';', $expr, 2; # We can explicitly define variables by enumerating them
1045 my @vars = ( $vars || $expr ) =~ m/([\$\%\@]\w+)/g; # Extract variables from varlist or expression
1046 $expr //= $vars; # By default just dump variables
1047 @vars = keys %{{ map{ $_ => 1 } @vars }}; # Make vars uniq
1048  
1049 # PadWalder returns references to variables. We derefference them at
1050 # our subroutine. Thus we able to evalutate @array, %hash variables
1051 # along with $scalar
1052 $vars = ''; my $idx = 0;
1053 for( @vars ) {
1054 m/^([\$\@\%])/;
1055 # TODO: Create alias'es instead of new variables
1056 $vars .= "\tmy $_ = $1\{ \$_[$idx] };\n";
1057 $idx++;
1058 }
1059  
1060 # TODO: We should eval at user's package to make sub_name( ... ) work
1061 # Currently we must use Package::Name::sub_name( ... )
1062 my $result = eval "return sub{ \n$vars\t$expr\n }";
1063 DB::say( $@ ), return 1 if $@;
1064  
1065  
1066 # Replace variables by theirs values
1067 for( @vars ) {
1068 ($_ = $my ->{ $_ }), next if exists $my ->{ $_ };
1069 ($_ = $our->{ $_ }), next if exists $our->{ $_ };
1070  
1071 DB::say "Variable '$_' does not exists at this scope";
1072 $_ = \undef;
1073 }
1074  
1075 DB::say DB::dumper $_ for $result->( @vars );
1076 }
1077  
1078 return 1;
1079 }
1080  
1081  
1082  
1083 sub cmd_edit_file {
1084 die 'You should setup EDITOR environment variable' unless $ENV{ EDITOR };
1085  
1086 ## INIT
1087 my( $file, $line, $editor_args ) = shift =~ m/^${file_line}?(.*)$/;
1088 $editor_args //= '';
1089  
1090 if( !defined $line ) {
1091 $line = DB::state( 'list.line' ) -1;
1092  
1093 # Put cursor at required line. EDITOR should center scroll to this line
1094 $line -= defined DB::state( 'list.level' )? $lines_before : $lines_after;
1095 }
1096 $line = ':' .$line;
1097  
1098 $file = current_file( $file ) =~ s/^~/$DB::options{ pwd }/r;
1099 $file = `realpath --relative-base $ENV{ PWD } $file`;# Get relative to current symlink
1100 $file =~ s/\n$//; # Strip new lines at the end
1101 $file = "$ENV{ PWD }/$file" unless $file =~ m#^/#; # Make path absolute
1102  
1103  
1104 ## Run editor
1105 my $cmd = "$ENV{ EDITOR } $editor_args $file" .($ENV{EDITOR_NOLINE}?'':$line);
1106 DB::say "Run: $cmd" if DB::state( 'ddd' ) &1;
1107 `$cmd`;
1108  
1109  
1110 1;
1111 }
1112  
1113  
1114  
1115 set_command interact => \&interact;
1116  
1117 set_command mdump => \&cmd_mdump;
1118 set_command print_eval => \&cmd_print_eval;
1119 set_command e => \&cmd_dump_eval, 'eval';
1120 set_command ddp => \&cmd_ddp;
1121 set_command peek => \&cmd_peek;
1122 set_command q => \&cmd_quit, 'quit';
1123 set_command s => \&cmd_step, 'step';
1124 set_command n => \&cmd_stepover, 'stepover';
1125 set_command r => \&cmd_stepout, 'stepout';
1126 set_command go => \&cmd_continue;
1127 set_command b => \&cmd_breakpoint, 'breakpoint';
1128 set_command a => \&cmd_action, 'action';
1129 set_command f => \&cmd_files, 'files';
1130 set_command l => \&cmd_list, 'list';
1131 set_command T => \&cmd_stack_trace;
1132 set_command d => \&cmd_debug_expr, 'debug';
1133 set_command vars => \&cmd_variables, 'variables';
1134  
1135 set_command ge => \&cmd_edit_file;
1136 set_command z => sub{
1137 DB::stop;
1138 DB::traps;
1139 1;
1140 return;
1141 };
1142  
1143  
1144 DB::on( trap => \&breakpoint_handler );
1145 DB::on( trap => \&action_handler );
1146 1;