ART/API/Vim.pm untested

filter: Statementstmt 0.0% 0 / 145 Branchbran 0.0% 0 / 36 Conditioncond 0.0% 0 / 24 MC/DCmcdc 0.0% 0 / 13 Subroutinesub 0.0% 0 / 15 Podpod 0.0% 0 / 8 totaltotal 0.0% 0 / 241 CC 19 SCAR 32.6
CC
19
Cov
0%
classify_var_at
56.0
_Perl_to_VimScript
42.0
analyze_code
30.0
CRAP 26.1
1 package Code::ART::API::Vim;
2  
3 use 5.016;
4 use warnings;
5 use Scalar::Util qw< looks_like_number >;
6 use List::Util qw< min max >;
7  
8 our $VERSION = '0.000001';
9  
10 # We'll need the core functionality...
11 use Code::ART ();
12  
13 # Load the module...
14 sub import {
15 # Export the API...
16 no strict 'refs';
17 *{caller().'::refactor_to_sub'} = \&refactor_to_sub;
18 *{caller().'::classify_var_at'} = \&classify_var_at;
19 *{caller().'::find_expr_scope'} = \&find_expr_scope;
20 *{caller().'::analyze_code'} = \&analyze_code;
21 }
22  
23 sub refactor_to_sub {
24 # Unpack any options...
25 my $opt_ref = shift // {};
26  
27 # Grab the source code, which will be sent through the input filestream...
28 my $source = do{ local $/; readline(*ARGV) };
29  
30 # Ask Code::ART to do the actual refactoring...
31 my $refactoring = Code::ART::refactor_to_sub($source, $opt_ref);
32  
33 # if ($refactoring->{failed}) {
34 # $refactoring->{reason} = $refactoring->{failed};
35 # $refactoring->{failed} = 1;
36 # }
37  
38 say _Perl_to_VimScript( $refactoring );
39 }
40  
41 sub analyze_code {
42 # Load code to be analyzed...
43 my $source = do { local $/; readline(*ARGV); };
44  
45 # Do the full classification...
46 my $classification = Code::ART::classify_all_vars_in($source);
47 print _Perl_to_VimScript($classification) and return if $classification->{failed};
48  
49 # Generate a pattern to match all variables with various interesting properties...
50 my (@cacograms, @undeclared_vars, @unused_vars);
51 for my $var (values %{$classification->{vars}}) {
52 # Collect cacograms (names that don't help you understand)...
53 if ($var->{is_cacogram} && $var->{declared_at}) {
54 push @cacograms, _line_and_column_from_ID($source, [$var->{declared_at}])
55 . $var->{sigil} . $var->{raw_name};
56 }
57  
58 # Collect undeclared variables...
59 if ($var->{declared_at} < 0 && !$var->{is_builtin} && $var->{raw_name} !~ /[:']/) {
60 push @undeclared_vars, _line_and_column_from_ID($source, [keys %{ $var->{used_at}}])
61 . $var->{sigil} . $var->{raw_name};
62 }
63 # Collect unused variables...
64 elsif (!keys %{$var->{used_at}}) {
65 push @unused_vars, _line_and_column_from_ID($source, [$var->{declared_at}])
66 . $var->{sigil} . $var->{raw_name};
67 }
68 }
69  
70 # Output all the gathered information...
71 print _Perl_to_VimScript({
72 cacograms => join('\|', @cacograms),
73 undeclared_vars => join('\|', @undeclared_vars),
74 unused_vars => join('\|', @unused_vars),
75 });
76 }
77  
78 my $VimOWS = '\%(\_s*\%(#.*\_s*\)*\)';
79 sub classify_var_at {
80 # Unpack the specified variable position (i.e. the byte number in the buffer)
81 my ($cursor_byte) = @_;
82  
83 # Grab the source code, which will be sent through the input filestream...
84 my $source = do { local $/; readline(*ARGV); };
85  
86 # Ask Code::ART to do the actual classification
87 # (making allowance for the fact that Vim byte numbers start at 1,
88 # but Perl string indexes start at zero)...
89 my $info = Code::ART::_classify_var_at($source, $cursor_byte - 1);
90  
91 # Make sure the resulting information has valid 'sigil' entry...
92 $info->{sigil} //= q{};
93  
94 # Convert the various locations found to Vim line/column coordinates...
95 $info->{matchloc} = _line_and_column_from_ID($source,
96 [$info->{declared_at}, keys %{$info->{used_at}}]);
97 $info->{declloc} = _line_and_column_from_ID($source, [$info->{declared_at}]);
98  
99 # Convert scope details to Vim formats...
100 my $min_scope
101 = $info->{declared_at} >= 0 ? _linenum_from_ID($source, $info->{declared_at})
102 : 1;
103 my $max_scope = _linenum_from_ID($source, $info->{end_of_scope});
104 $info->{scopeloc} = '\%>' . ($min_scope-1) . 'l'
105 . '\%<' . ($max_scope+1) . 'l';
106 $info->{scope_size} = $max_scope - $min_scope + 1;
107  
108 # Work out the correct Vim regex to match the valid sigils
109 # of the various declinations of the variable...
110 my $sigil_matcher = $info->{sigil} eq '@' ? '\%(\$#\|[@$%]\)'
111 : $info->{sigil} eq '%' ? '[%$@]'
112 : $info->{sigil} eq '$' ? '\$#\@!'
113 : '';
114  
115 # Build the complete Vim regex for matching any instance of the variable...
116 $info->{matchname}
117 = $info->{failed}
118 ? q{}
119 : $sigil_matcher.$VimOWS.'\%('.$info->{raw_name}
120 .'\|{'.$VimOWS.$info->{raw_name}.$VimOWS.'}\)'
121 ;
122  
123 # Build the complete Vim regex for matching just the name of any instance of the variable...
124 $info->{matchnameonly}
125 = $info->{failed}
126 ? q{}
127 : $sigil_matcher.$VimOWS.'\%(\zs'.$info->{raw_name}
128 .'\ze\|{'.$VimOWS.'\zs'.$info->{raw_name}.'\ze'.$VimOWS.'}\)'
129 ;
130  
131 # Convert homogram and parogram data to searchable regexes...
132 for my $gram_type (qw< homograms parograms >) {
133 my $grams = $info->{$gram_type};
134 use Data::Dump 'ddx';
135 $info->{$gram_type}
136 = join('\|', map { my $gram = $grams->{$_};
137 my $from = _linenum_from_ID($source, $gram->{from}) - 1;
138 my $to = _linenum_from_ID($source, $gram->{to} ) + 1;
139 '\%>'.$from.'l\%<'.$to.'l\%($#\?\|[%@]\)'.$VimOWS.$_;
140 }
141 keys %{$grams});
142 }
143  
144 # Convert all that information to a Vim dictionary, and output it...
145 say _Perl_to_VimScript($info);
146 }
147  
148 sub find_expr_scope {
149 my ($from, $to, $match_all) = @_;
150  
151 # Grab the source code, which will be sent through the input filestream...
152 my $source = do { local $/; readline(*ARGV); };
153  
154 my $expr_scope = Code::ART::find_expr_scope($source, $from-1, $to-1, $match_all);
155 if ($expr_scope->{failed}) {
156 print _Perl_to_VimScript($expr_scope);
157 return;
158 }
159  
160 # Convert individual match locations to a single Vim regex...
161 my $matchloc = _line_and_column_from_ID(
162 $source,
163 [map { $_->{from} } @{$expr_scope->{matches}}],
164 [map { '\_.\{'.$_->{length}.'}' } @{$expr_scope->{matches}}],
165 );
166 my $firstloc = _line_and_column_from_ID( $source, [ $expr_scope->{matches}[0]{from} ] );
167  
168 $expr_scope->{use_version} = $expr_scope->{use_version}->numify;
169  
170 print _Perl_to_VimScript({
171 matchloc => $matchloc,
172 firstloc => $firstloc,
173 matchcount => 0+@{$expr_scope->{matches}},
174 %{$expr_scope},
175 });
176 }
177  
178 sub _Perl_to_VimScript {
179 my ($value) = @_;
180 if (ref($value) eq 'HASH') {
181 return '{'
182 . join( q{, }, map { qq{'$_' : }._Perl_to_VimScript($value->{$_}) } keys %{$value})
183 . '}';
184 }
185 elsif (ref($value) eq 'ARRAY') {
186 return '[' . join( q{, }, map { _Perl_to_VimScript($_) } @{$value} ) . ']';
187 }
188 elsif (!defined $value) {
189 return q{''};
190 }
191 elsif ($value =~ m{\A \s*+ [+-]?+ \d++ (?: [.]?+ \d*+) ([eE] [+-]?+ \d+)?+ \s*+ \Z}xms) {
192 return $value;
193 }
194 elsif ($value =~ /\n/) {
195 $value =~ s{\\}{\\\\}g;
196 $value =~ s{\n}{\\n}g;
197 $value =~ s{"}{\\"}g;
198 return qq{"$value"};
199 }
200 else {
201 $value =~ s{'}{''}g;
202 return qq{'$value'};
203 }
204 }
205  
206 sub _linenum_from_ID {
207 my ($source, $id) = @_;
208  
209 my $prefix = substr($source, 0, $id);
210 $prefix =~ m{(.*)\z};
211 return 1 + $prefix =~ tr/\n//;
212 }
213  
214 sub _line_and_column_from_ID {
215 my ($source, $ids_ref, $etc_ref) = @_;
216 my @ids = @{ $ids_ref // [] };
217 my @etc = @{ $etc_ref // [] };
218 my @positions; # Accumulates converted position coordinates
219  
220 # Convert each ID (a Perl string index) to a Vim line/column coordinate
221 @ids = sort {$a <=> $b} @ids;
222 for my $id (@ids) {
223 # Grab any per-ID suffix to be appended to each location constraint...
224 my $etc = shift(@etc) // q{};
225  
226 # Skip any undeclared variables...
227 next if !$id || $id < 0;
228  
229 # The line and column are determined by what preceded the specified position...
230 my $prefix = substr($source, 0, $id);
231 $prefix =~ m{(.*)\z};
232 my $col = 1 + length($1);
233 my $line = 1 + $prefix =~ tr/\n//;
234  
235 # Remember the conversion...
236 push @positions, '\%'.$line.'l\%'.$col.'c'.$etc;
237 }
238  
239 # If there were no valid positions, there's no need for a Vim regex...
240 return '' if !@positions;
241  
242 # Otherwise, build the regex as the disjunction of each possible set of coordinates...
243 return '\%(' . join('\|', @positions) . '\)';
244 }
245  
246  
247  
248 1; # Magic true value required at end of module
249 __END__