blib/lib/B/DeparseTree/SyntaxTree.pm untested

filter: Statementstmt 0.0% 0 / 244 Branchbran 0.0% 0 / 138 Conditioncond 0.0% 0 / 50 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 16 Podpod 0.0% 0 / 14 totaltotal 0.0% 0 / 462 SCAR 85.1
CC
70
Cov
0%
template_engine
756.0
info_from_template
110.0
info2str
90.0
CRAP 4970.0
1 # B::DeparseTree tree-building routines.
2 # Copyright (c) 2018 Rocky Bernstein
3 # All rights reserved.
4 # This module is free software; you can redistribute and/or modify
5 # it under the same terms as Perl itself.
6  
7 # This is based on the module B::Deparse by Stephen McCamant.
8 # It has been extended save tree structure, and is addressible
9 # by opcode address.
10  
11 # Note the package name. It is *not* B::DeparseTree::Tree.
12 # In the future there may be a version of this that doesn't
13 # save as much information, but just stores enough to extract
14 # a string, which would be a slightly more heavyweight version of
15 # B::Deparse.
16 package B::DeparseTree::SyntaxTree;
17  
18 use B::DeparseTree::Node;
19  
20 our($VERSION, @EXPORT, @ISA);
21 $VERSION = '3.2.0';
22 @ISA = qw(Exporter B::DeparseTree);
23 @EXPORT = qw(
24 combine
25 combine2str
26 get_info_and_str
27 expand_simple_spec
28 indent_less
29 indent_more
30 indent_value
31 info2str
32 info_from_list
33 info_from_template
34 info_from_string
35 info_from_text
36 template_engine
37 template2str
38 );
39  
40 sub combine($$$)
41 {
42 my ($self, $sep, $items) = @_;
43 # FIXME: loop over $item, testing type.
44 Carp::confess("should be a reference to a array: is $items") unless
45 ref $items eq 'ARRAY';
46 my @result = ();
47 foreach my $item (@$items) {
48 my $add;
49 if (ref $item) {
50 if (ref $item eq 'ARRAY' and scalar(@$item) == 2) {
51 $add = [$item->[0], $item->[1]];
52 } elsif (eval{$item->isa("B::DeparseTree::Node")}) {
53 $add = [$item->{text}, $item->{addr}];
54 # First item is text and second item is op address.
55 } else {
56 Carp::confess("don't know what to do with $item");
57 }
58 } else {
59 $add = $item;
60 }
61 push @result, $sep if @result && $sep;
62 push @result, $add;
63 }
64 return @result;
65 }
66  
67 sub combine2str($$$)
68 {
69 my ($self, $sep, $items) = @_;
70 my $result = '';
71 foreach my $item (@$items) {
72 $result .= $sep if $result;
73 if (ref $item) {
74 if (ref $item eq 'ARRAY' and scalar(@$item) == 2) {
75 # First item is text and second item is op address.
76 $result .= $self->info2str($item->[0]);
77 } elsif (eval{$item->isa("B::DeparseTree::Node")}) {
78 if (exists $item->{fmt}) {
79 $result .= $self->template2str($item);
80 } else {
81 $result .= $self->info2str($item);
82 }
83 } else {
84 Carp::confess("Invalid ref item ref($item)");
85 }
86 } else {
87 # FIXME: add this and remove errors
88 if (index($item, '@B::DeparseTree::Node') > 0) {
89 Carp::confess("\@B::DeparseTree::Node as an item is probably wrong");
90 }
91 $result .= $item;
92 }
93 }
94 return $result;
95 }
96  
97 sub expand_simple_spec($$)
98 {
99 my ($self, $fmt) = @_;
100 my $result = '';
101 while ((my $k=index($fmt, '%')) >= 0) {
102 $result .= substr($fmt, 0, $k);
103 my $spec = substr($fmt, $k, 2);
104 $fmt = substr($fmt, $k+2);
105  
106 if ($spec eq '%%') {
107 $result .= '%';
108 } elsif ($spec eq '%+') {
109 $result .= $self->indent_more();
110 } elsif ($spec eq '%-') {
111 $result .= $self->indent_less();
112 } elsif ($spec eq '%|') {
113 $result .= $self->indent_value();
114 } else {
115 Carp::confess("Unknown spec $spec")
116 }
117 }
118 $result .= $fmt if $fmt;
119 return $result;
120 }
121  
122 sub indent_less($$) {
123 my ($self, $check_level) = @_;
124 $check_level = 0 if !defined $check_level;
125  
126 $self->{level} -= $self->{'indent_size'};
127 my $level = $self->{level};
128 if ($check_level < 0) {
129 Carp::confess("mismatched indent/dedent") if $check_level;
130 $level = 0;
131 $self->{level} = 0;
132 }
133 return $self->indent_value();
134 }
135  
136 sub indent_more($) {
137 my ($self) = @_;
138 $self->{level} += $self->{'indent_size'};
139 return $self->indent_value();
140 }
141  
142 sub indent_value($) {
143 my ($self) = @_;
144 my $level = $self->{level};
145 if ($self->{'use_tabs'}) {
146 return "\t" x ($level / 8) . " " x ($level % 8);
147 } else {
148 return " " x $level;
149 }
150 }
151  
152 sub info2str($$)
153 {
154 my ($self, $item) = @_;
155 my $result = '';
156 if (ref $item) {
157 if (ref $item eq 'ARRAY' and scalar(@$item) == 2) {
158 # This code is going away...
159 Carp::confess("fixme");
160 $result = $item->[0];
161 } elsif (eval{$item->isa("B::DeparseTree::Node")}) {
162 if (exists $item->{fmt}) {
163 $result .= $self->template2str($item);
164 if ($item->{maybe_parens}) {
165 my $mp = $item->{maybe_parens};
166 if ($mp->{force} || $mp->{parens}) {
167 $result = "($result)";
168 }
169 }
170 } elsif (!exists $item->{texts} && exists $item->{text}) {
171 # Is a constant string
172 $result .= $item->{text};
173 } else {
174 $result = $self->combine2str($item->{sep},
175 $item->{texts});
176 }
177  
178 } else {
179 Carp::confess("Invalid ref item ref($item)");
180 }
181 } else {
182 # FIXME: add this and remove errors
183 if (index($item, '@B::DeparseTree::Node') > 0) {
184 Carp::confess("\@B::DeparseTree::Node as an item is probably wrong");
185 }
186 $result = $item;
187 }
188 return $result;
189 }
190  
191 # Create an info structure from a list of strings
192 # FIXME: $deparse (or rather $self) should be first
193 sub info_from_list($$$$$$)
194 {
195 my ($op, $self, $texts, $sep, $type, $opts) = @_;
196  
197 # Set undef in "texts" argument position because we are going to create
198 # our own text from the $texts.
199 my $info = B::DeparseTree::Node->new($op, $self, $texts, undef,
200 $type, $opts);
201 $info->{sep} = $sep;
202 my $text = '';
203 foreach my $item (@$texts) {
204 $text .= $sep if $text and $sep;
205 if(ref($item) eq 'ARRAY'){
206 $text .= $item->[0];
207 } elsif (eval{$item->isa("B::DeparseTree::Node")}) {
208 $text .= $item->{text};
209 } else {
210 $text .= $item;
211 }
212 }
213  
214 $info->{text} = $text;
215 if ($opts->{maybe_parens}) {
216 my ($obj, $context, $precedence) = @{$opts->{maybe_parens}};
217 my $parens = B::DeparseTree::Node::parens_test($obj, $context, $precedence);
218 $self->{maybe_parens} = {
219 context => $context,
220 precedence => $precedence,
221 force => $obj->{'parens'},
222 parens => $parens ? 'true' : ''
223 };
224 $info->{text} = "($info->{text})" if exists $info->{text} and $parens;
225 }
226  
227 return $info
228 }
229  
230 # Create an info structure a template pattern
231 sub info_from_template($$$$$) {
232 my ($self, $type, $op, $fmt, $indexes, $args, $opts) = @_;
233 $opts = {} unless defined($opts);
234 my @args = @$args;
235 my $info = B::DeparseTree::Node->new($op, $self, $args, undef, $type, $opts);
236  
237 $indexes = [0..$#args] unless defined $indexes;
238 $info->{'indexes'} = $indexes;
239 my $text = $self->template_engine($fmt, $indexes, $args);
240  
241 $info->{'fmt'} = $fmt;
242 $info->{'text'} = $self->template_engine($fmt, $indexes, $args);
243  
244 if (! defined $op) {
245 $info->{addr} = ++$self->{'last_fake_addr'};
246 $self->{optree}{$info->{addr}} = $info;
247 }
248  
249 if ($opts->{'relink_children'}) {
250 # FIXME we should specify which children to relink
251 for (my $i=0; $i < scalar @$args; $i++) {
252 if ($args[$i]->isa("B::DeparseTree::Node")) {
253 $args[$i]{parent} = $info->{addr};
254 }
255 }
256 }
257  
258 # Link the parent of Deparse::Tree::Nodes to this node.
259 if ($opts->{'synthesized_nodes'}) {
260 foreach my $node (@{$opts->{'synthesized_nodes'}}) {
261 $node->{parent} = $info->{addr};
262 }
263 }
264  
265 # Need to handle maybe_parens since B::DeparseNode couldn't do that
266 # as it was passed a ref ARRAY rather than a string.
267 if ($opts->{maybe_parens}) {
268 my ($obj, $context, $precedence) = @{$opts->{maybe_parens}};
269 my $parens = B::DeparseTree::Node::parens_test($obj,
270 $context, $precedence);
271 $info->{maybe_parens} = {
272 context => $context,
273 precedence => $precedence,
274 force => $obj->{'parens'},
275 parens => $parens ? 'true' : ''
276 };
277 $info->{text} = "($info->{text})" if exists $info->{text} and $parens;
278 }
279  
280 return $info;
281 }
282  
283 # Create an info structure from a single string
284 sub info_from_string($$$$$)
285 {
286 my ($self, $type, $op, $str, $opts) = @_;
287 $opts ||= {};
288 return B::DeparseTree::Node->new($op, $self, $str, undef,
289 $type, $opts);
290 }
291  
292 # OBSOLETE: Create an info structure from a single string
293 # FIXME: remove this
294 sub info_from_text($$$$$)
295 {
296 my ($op, $self, $text, $type, $opts) = @_;
297 # Use this to smoke outt calls
298 # use Enbugger 'trepan'; Enbugger->stop;
299 return $self->info_from_string($type, $op, $text, $opts)
300 }
301  
302 # List of suffix characters that are handled by "expand_simple_spec()".
303 use constant SIMPLE_SPEC => '%+-|';
304  
305 # Extract the string at $args[$index] and if
306 # we are looking for that position include where we are in
307 # that position
308 sub get_info_and_str($$$)
309 {
310 my ($self, $index, $args) = @_;
311 my $info = $args->[$index];
312 my $str = $self->info2str($info);
313 return ($info, $str);
314 }
315  
316 sub template_engine($$$$)
317 {
318 my ($self, $fmt, $indexes, $args, $find_addr) = @_;
319  
320 # use Data::Dumper;
321 # print "-----\n";
322 # p $args;
323 # print "'======\n";
324 # print $fmt, "\n"
325 # print $args, "\n";
326  
327 my $i = 0;
328 $find_addr = -2 unless $find_addr;
329  
330 my $start_fmt = $fmt; # used in error messages
331 my @args = @$args;
332  
333 my $result = '';
334 my $find_pos = undef;
335 while ((my $k=index($fmt, '%')) >= 0) {
336 $result .= substr($fmt, 0, $k);
337 my $spec = substr($fmt, $k, 2);
338 $fmt = substr($fmt, $k+2);
339  
340 if (index(SIMPLE_SPEC, substr($spec, 1, 1)) >= 0) {
341 $result .= $self->expand_simple_spec($spec);
342 } elsif ($spec eq "%c") {
343 # Insert child entry
344  
345 # FIXME: turn this into a subroutine.
346 if ($i >= scalar @{$indexes}) {
347 Carp::confess("Need another entry in args_spec for %c in fmt: $start_fmt");
348 }
349 my $index = $indexes->[$i++];
350 if ($index >= scalar @args) {
351 Carp::confess("$index in $start_fmt for %c is too large; should be less " .
352 "than scalar(@args)");
353 }
354 my $str;
355 my ($info, $str) = $self->get_info_and_str($index, $args);
356 if (ref($info) && $info->{'addr'} == $find_addr) {
357 my $len = length($result);
358 $len++ if (exists $info->{maybe_parens}
359 && $info->{maybe_parens}{parens});
360 $find_pos = [$len, length($str)];
361 }
362 $result .= $str;
363 } elsif ($spec eq "%C") {
364 # Insert separator between child entry lists
365 my ($low, $high, $sub_spec) = @{$indexes->[$i++]};
366 my $sep = $self->expand_simple_spec($sub_spec);
367 my $list = '';
368 for (my $j=$low; $j<=$high; $j++) {
369 $result .= $sep if $j > $low;
370  
371 # FIXME: Remove duplicate code
372 my ($info, $str) = $self->get_info_and_str($j, $args);
373 if (ref($info) && $info->{'addr'} == $find_addr) {
374 my $len = length($result);
375 $len++ if (exists $info->{maybe_parens}
376 && $info->{maybe_parens}{parens});
377 $find_pos = [$len, length($str)];
378 }
379 $result .= $str;
380 }
381 } elsif ($spec eq "%f") {
382 # Run maybe_parens_func
383 my $fn_name = shift @args;
384 my ($cx, $prec) = @{$indexes->[$i++]};
385 my $params = $self->template_engine("%C", [[0, $#args], ', ']);
386 $result .= B::Deparse::maybe_parens_func($self, $fn_name, $params, $cx, $prec);
387 } elsif ($spec eq "%F") {
388 # Run a transformation function
389 if ($i >= scalar@$indexes) {
390 Carp::confess("Need another entry in args_spec for %%F fmt: $start_fmt");
391 }
392 my ($arg_index, $transform_fn) = @{$indexes->[$i++]};
393 if ($arg_index >= scalar @args) {
394 Carp::confess("argument index $arg_index in $start_fmt for %%F is too large; should be less than @$args");
395 }
396 if (ref($transform_fn ne 'CODE')) {
397 Carp::confess("transformation function $transform_fn is not CODE");
398 }
399 my ($arg) = $args[$arg_index];
400 $result .= $transform_fn->($arg);
401  
402 } elsif ($spec eq "%;") {
403 # Insert semicolons and indented newlines between statements.
404 # Don't insert them around empty strings - some OPs
405 # don't have an text associated with them.
406 # Finally, replace semicolon a the end of statement that
407 # end in "}" with a \n and proper indent.
408 my $sep = $self->expand_simple_spec(";\n%|");
409 my $start_size = length($result);
410 for (my $j=0; $j< @args; $j++) {
411 my $old_result = $result;
412 if ($j > 0 && length($result) > $start_size) {
413 # Remove any prior ;\n
414 $result = substr($result, 0, -1) if substr($result, -1) eq "\n";
415 $result = substr($result, 0, -1) if substr($result, -1) eq ";";
416 ## The below needs to be done based on whether the previous construct is a compound statement or not.
417 ## That could be added in a trailing format specifier for it.
418 ## "sub {...}" and "$h = {..}" need a semicolon while "if () {...}" doesn't.
419 # if (substr($result, -1) eq "}" & $j < $#args) {
420 # # Omit ; from sep. FIXME: do this based on an option?
421 # $result .= substr($sep, 1);
422 # } else {
423 # $result .= $sep;
424 # }
425 $result .= $sep;
426 }
427  
428 # FIXME: Remove duplicate code
429 my ($info, $str) = $self->get_info_and_str($j, $args);
430 if (ref($info) && $info->{'addr'} == $find_addr) {
431 my $len = length($result);
432 $len++ if exists $info->{maybe_parens} and $info->{maybe_parens}{parens};
433 $find_pos = [length($result), length($str)];
434 }
435 if (!$str) {
436 $result = $old_result;
437 } else {
438 $result .= $str
439 }
440 }
441 # # FIXME: Add the final ';' based on an option?
442 # if ($result and not
443 # (substr($result, -1) eq ';' or
444 # (substr($result, -1) eq ';\n'))) {
445 # $result .= ';' if $result and substr($result, -1) ne ';';
446 # }
447  
448 } elsif ($spec eq "\cS") {
449 # FIXME: not handled yet
450 ;
451 } else {
452 # We have % with a non-special symbol. Just preserve those.
453 $result .= $spec;
454 }
455 }
456 $result .= $fmt if $fmt;
457 if ($find_addr != -2) {
458 # want result and position
459 return $result, $find_pos;
460 }
461 # want just result
462 return $result;
463  
464 }
465  
466 sub template2str($$) {
467 my ($self, $info) = @_;
468 return $self->template_engine($info->{fmt},
469 $info->{indexes},
470 $info->{texts});
471 }
472  
473 1;