Add PRE_ATTR and use it for array indices.
[p5sagit/Devel-Size.git] / memnodes.pl
1 #!/usr/bin/env perl
2
3 use strict;
4 use warnings;
5 use autodie;
6
7 use DBI qw(looks_like_number);
8 use DBD::SQLite;
9 use JSON::XS;
10 use Devel::Dwarn;
11
12 use Getopt::Long;
13
14 # XXX import these from the XS code
15 use constant NPtype_NAME     => 0x01;
16 use constant NPtype_LINK     => 0x02;
17 use constant NPtype_SV       => 0x03;
18 use constant NPtype_MAGIC    => 0x04;
19 use constant NPtype_OP       => 0x05;
20
21 use constant NPattr_LEAFSIZE => 0x00;
22 use constant NPattr_NAME     => 0x01;
23 use constant NPattr_PADFAKE  => 0x02;
24 use constant NPattr_PADNAME  => 0x03;
25 use constant NPattr_PADTMP   => 0x04;
26 use constant NPattr_NOTE     => 0x05;
27 use constant NPattr_PRE_ATTR => 0x06;
28
29
30 GetOptions(
31     'text!' => \my $opt_text,
32     'dot=s' => \my $opt_dot,
33     'db=s'  => \my $opt_db,
34     'verbose|v!' => \my $opt_verbose,
35     'debug|d!' => \my $opt_debug,
36     'showid!' => \my $opt_showid,
37 ) or exit 1;
38
39 my $j = JSON::XS->new->ascii->pretty(0);
40
41 my ($dbh, $node_ins_sth);
42 if ($opt_db) {
43     $dbh = DBI->connect("dbi:SQLite:dbname=$opt_db","","", {
44         RaiseError => 1, PrintError => 0, AutoCommit => 0
45     });
46     $dbh->do("PRAGMA synchronous = OFF");
47     $dbh->do("DROP TABLE IF EXISTS node");
48     $dbh->do(q{
49         CREATE TABLE node (
50             id integer primary key,
51             name text,
52             title text,
53             type integer,
54             depth integer,
55             parent_id integer,
56
57             self_size integer,
58             kids_size integer,
59             kids_node_count integer,
60             child_ids text,
61             attr_json text,
62             leaves_json text
63         )
64     });
65     $node_ins_sth = $dbh->prepare(q{
66         INSERT INTO node VALUES (?,?,?,?,?,?,  ?,?,?,?,?,?)
67     });
68 }
69
70 my @stack;
71 my %seqn2node;
72
73 use HTML::Entities qw(encode_entities);;
74 my $dotnode = sub {
75     my $name = encode_entities(shift);
76     $name =~ s/"/\\"/g;
77     return '"'.$name.'"';
78 };
79
80
81 my $dot_fh;
82 if ($opt_dot) {
83     open $dot_fh, ">$opt_dot";
84     print $dot_fh "digraph {\n"; # }
85     print $dot_fh "graph [overlap=false]\n"; # target="???", URL="???"
86 }
87
88 sub fmt_size {
89     my $size = shift;
90     my $kb = $size / 1024;
91     return $size if $kb < 5;
92     return sprintf "%.1fKb", $kb if $kb < 1000;
93     return sprintf "%.1fMb", $kb/1024;
94 }
95
96
97 sub enter_node {
98     my $x = shift;
99
100     my $parent = $stack[-1];
101     if ($parent) {
102
103         if ($parent->{name} eq 'SV(PVAV)') {
104             Dwarn $x->{attr};
105             my $index = $x->{attr}{index};
106             # If node is an AVelem of a CvPADLIST propagate pad name to AVelem
107             if (@stack >= 4 and (my $cvpl = $stack[-4])->{name} eq 'CvPADLIST') {
108                 # cache the pad names so we can eat them in order
109                 my $padnames = $cvpl->{_cached}{padnames} ||= do {
110                     my @names = @{ $cvpl->{attr}{+NPattr_PADNAME} || []};
111                     $_ = "my(".($_||'').")" for @names;
112                     $names[0] = '@_';
113                     \@names;
114                 };
115                 #die Dwarn $x;
116                 $x->{name} = $padnames->[$index] || "?";
117                 $x->{name} =~ s/my\(SVs_PADTMP\)/PADTMP/; # XXX hack for neatness
118             }
119             else {
120                 $x->{name} = "[$index]";
121             }
122         }
123     }
124
125     return $x;
126 }
127
128
129 sub leave_node {
130     my $x = shift;
131     delete $seqn2node{$x->{id}};
132
133     my $self_size = 0; $self_size += $_  for values %{$x->{leaves}};
134     $x->{self_size} = $self_size;
135
136     my $parent = $stack[-1];
137     if ($parent) {
138         # link to parent
139         $x->{parent_id} = $parent->{id};
140         # accumulate into parent
141         $parent->{kids_node_count} += 1 + ($x->{kids_node_count}||0);
142         $parent->{kids_size} += $self_size + $x->{kids_size};
143         push @{$parent->{child_id}}, $x->{id};
144     }
145
146     # output
147     # ...
148     if ($opt_dot) {
149         printf "// n%d parent=%s(type=%s)\n", $x->{id},
150                 $parent ? $parent->{id} : "",
151                 $parent ? $parent->{type} : ""
152             if 0;
153         if ($x->{type} != NPtype_LINK) {
154             my $name = $x->{title} ? "\"$x->{title}\" $x->{name}" : $x->{name};
155
156             if ($x->{kids_size}) {
157                 $name .= sprintf " %s+%s=%s", fmt_size($x->{self_size}), fmt_size($x->{kids_size}), fmt_size($x->{self_size}+$x->{kids_size});
158             }
159             else {
160                 $name .= sprintf " +%s", fmt_size($x->{self_size});
161             }
162             $name .= " $x->{id}" if $opt_showid;
163
164             my @node_attr = (
165                 sprintf("label=%s", $dotnode->($name)),
166                 "id=$x->{id}",
167             );
168             my @link_attr;
169             #if ($x->{name} eq 'hek') { push @node_attr, "shape=point"; push @node_attr, "labelfontsize=6"; }
170             if ($parent) { # probably a link
171                 my $parent_id = $parent->{id};
172                 my @link_attr = ("id=$parent_id");
173                 if ($parent->{type} == NPtype_LINK) { # link
174                     (my $link_name = $parent->{name}) =~ s/->$//;
175                     push @link_attr, (sprintf "label=%s", $dotnode->($link_name));
176                     $parent_id = ($stack[-2]||die "panic")->{id};
177                 }
178                 printf $dot_fh qq{n%d -> n%d [%s];\n},
179                     $parent_id, $x->{id}, join(",", @link_attr);
180             }
181             printf $dot_fh qq{n%d [ %s ];\n}, $x->{id}, join(",", @node_attr);
182         }
183
184     }
185     if ($dbh) {
186         my $attr_json = $j->encode($x->{attr});
187         my $leaves_json = $j->encode($x->{leaves});
188         $node_ins_sth->execute(
189             $x->{id}, $x->{name}, $x->{title}, $x->{type}, $x->{depth}, $x->{parent_id},
190             $x->{self_size}, $x->{kids_size}, $x->{kids_node_count},
191             $x->{child_id} ? join(",", @{$x->{child_id}}) : undef,
192             $attr_json, $leaves_json,
193         );
194         # XXX attribs
195     }
196     return;
197 }
198
199 my $indent = ":   ";
200 my @attr_type_name = (qw(size NAME PADFAKE my PADTMP NOTE));
201 my $pending_pre_attr = {};
202
203 while (<>) {
204     chomp;
205
206     my ($type, $id, $val, $name, $extra) = split / /, $_, 5;
207
208     if ($type =~ s/^-//) {     # Node type ($val is depth)
209         printf "%s%s %s [#%d @%d]\n", $indent x $val, $name, $extra||'', $id, $val
210             if $opt_text;
211         while ($val < @stack) {
212             leave_node(my $x = pop @stack);
213             warn "N $id d$val ends $x->{id} d$x->{depth}: size $x->{self_size}+$x->{kids_size}\n"
214                 if $opt_verbose;
215         }
216         die "panic: stack already has item at depth $val"
217             if $stack[$val];
218         my $node = enter_node({
219             id => $id, type => $type, name => $name, extra => $extra,
220             attr => { %$pending_pre_attr },
221             leaves => {}, depth => $val, self_size=>0, kids_size=>0
222         });
223         %$pending_pre_attr = ();
224         $stack[$val] = $node;
225         $seqn2node{$id} = $node;
226     }
227     # --- Leaf name and memory size
228     elsif ($type eq "L") {
229         my $node = $seqn2node{$id} || die;
230         $node->{leaves}{$name} += $val;
231         printf "%s+%d %s\n", $indent x ($node->{depth}+1), $val, $name
232             if $opt_text;
233     }
234     # --- Attribute type, name and value
235     elsif (looks_like_number($type)) {
236         my $node = $seqn2node{$id} || die;
237         my $attr = $node->{attr} || die;
238
239         # attributes to queue up and apply to the next node
240         if (NPattr_PRE_ATTR == $type) {
241             $pending_pre_attr->{$name} = $val;
242         }
243         # attributes where the string is a key (or always empty and the type is the key)
244         elsif ($type == NPattr_NAME or $type == NPattr_NOTE) {
245             printf "%s~%s(%s) %d [t%d]\n", $indent x ($node->{depth}+1), $attr_type_name[$type], $name, $val, $type
246                 if $opt_text;
247             warn "Node $id already has attribute $type:$name (value $attr->{$type}{$name})\n"
248                 if exists $attr->{$type}{$name};
249             $attr->{$type}{$name} = $val || $id;
250             $node->{title} = $name if $type == 1 and !$val;
251         }
252         # attributes where the number is a key (or always zero)
253         elsif (NPattr_PADFAKE==$type or NPattr_PADTMP==$type or NPattr_PADNAME==$type) {
254             printf "%s~%s('%s') %d [t%d]\n", $indent x ($node->{depth}+1), $attr_type_name[$type], $name, $val, $type
255                 if $opt_text;
256             warn "Node $id already has attribute $type:$name (value $attr->{$type}[$val])\n"
257                 if defined $attr->{$type}[$val];
258             $attr->{+NPattr_PADNAME}[$val] = $name; # store all as NPattr_PADNAME
259         }
260         else {
261             printf "%s~%s %d [t%d]\n", $indent x ($node->{depth}+1), $name, $val, $type
262                 if $opt_text;
263             warn "Invalid attribute type '$type' on line $. ($_)";
264         }
265     }
266     else {
267         warn "Invalid type '$type' on line $. ($_)";
268         next;
269     }
270     $dbh->commit if $dbh and $id % 10_000 == 0;
271 }
272
273 my $top = $stack[0]; # grab top node before we pop all the nodes
274 leave_node(pop @stack) while @stack;
275 warn "EOF ends $top->{id} d$top->{depth}: size $top->{self_size}+$top->{kids_size}\n"
276     if $opt_verbose;
277 warn Dumper($top) if $opt_verbose;
278
279 if ($dot_fh) {
280     print $dot_fh "}\n";
281     close $dot_fh;
282     system("open -a Graphviz $opt_dot");
283 }
284
285 $dbh->commit if $dbh;
286
287 use Data::Dumper;
288 warn Dumper(\%seqn2node) if %seqn2node; # should be empty
289
290 =for
291 SV(PVAV) fill=1/1       [#1 @0] 
292 :   +64 sv =64 
293 :   +16 av_max =80 
294 :   AVelem->        [#2 @1] 
295 :   :   SV(RV)      [#3 @2] 
296 :   :   :   +24 sv =104 
297 :   :   :   RV->        [#4 @3] 
298 :   :   :   :   SV(PVAV) fill=-1/-1     [#5 @4] 
299 :   :   :   :   :   +64 sv =168 
300 :   AVelem->        [#6 @1] 
301 :   :   SV(IV)      [#7 @2] 
302 :   :   :   +24 sv =192 
303 192 at -e line 1.
304 =cut
305 __DATA__
306 N 1 0 SV(PVAV) fill=1/1
307 L 1 64 sv
308 L 1 16 av_max
309 N 2 1 AVelem->
310 N 3 2 SV(RV)
311 L 3 24 sv
312 N 4 3 RV->
313 N 5 4 SV(PVAV) fill=-1/-1
314 L 5 64 sv
315 N 6 1 AVelem->
316 N 7 2 SV(IV)
317 L 7 24 sv