blib/lib/Types/Algebraic.pm

filter: Statementstmt 100% 76 / 76 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 28 / 28 Podpod n/a totaltotal 100% 104 / 104 CC 1 SCAR 0.0
CC
1
Cov
100%
__ANON__
1.0
__ANON__
1.0
__ANON__
1.0
CRAP 1.0
↑ Summary
1 package Types::Algebraic;
2  
3 11 ▶use strict;
Subroutine __ANON__: called CC=1 SCAR=0.0
4 11 ▶use 5.022;
Subroutine __ANON__: called CC=1 SCAR=0.0
5 11 ▶use warnings;
Subroutine __ANON__: called CC=1 SCAR=0.0
6 our $VERSION = '0.07';
7  
8 11 ▶use Carp qw(croak confess);
Subroutine __ANON__: called CC=1 SCAR=0.0
9 11 ▶use Data::Dumper;
Subroutine __ANON__: called CC=1 SCAR=0.0
10 11 ▶use List::Util qw(all);
Subroutine __ANON__: called CC=1 SCAR=0.0
11 11 ▶use List::MoreUtils qw(pairwise zip_unflatten);
Subroutine __ANON__: called CC=1 SCAR=0.0
12 11 ▶use Keyword::Declare;
Subroutine __ANON__: called CC=1 SCAR=0.0
13 11 ▶use Keyword::Simple;
Subroutine __ANON__: called CC=1 SCAR=0.0
14 11 ▶use Moops;
Subroutine __ANON__: called CC=1 SCAR=0.0
15 11 ▶use PPR;
Subroutine __ANON__: called CC=1 SCAR=0.0
16 11 ▶use Scalar::Util qw(blessed);
Subroutine __ANON__: called CC=1 SCAR=0.0
17  
18 our $_RETURN_SENTINEL = \23;
19  
20 our %_KNOWN_CONSTRUCTORS;
21  
22 my ($expected, $fail_loc) = ('match statement', 0);
23 our $_TA_REGEX_LIB = qr{
24 (?(DEFINE)
25 (?<ADTPattern>
26 \( (?&PerlOWS)
27 (?{ $expected = "the name of a constructor", $fail_loc = pos() })
28 (?&PerlIdentifier) # constructor
29 (?{ $expected = "zero or more constructor arguments", $fail_loc = pos() })
30 (?:(?&PerlNWS) (?&ADTPatternSegment))* # 0 or more arguments
31 (?&PerlOWS)
32 \)
33 )
34  
35 (?<ADTPatternSegment>
36 (?:
37 \$ (?&PerlIdentifier) | # variable
38 (?&PerlIdentifier) | # constuctor without arguments
39 (?&ADTPattern) # constructor with arguments - requires parentheses
40 )
41 )
42 )
43  
44 $PPR::GRAMMAR
45 }xms;
46  
47 11 ▶class ADT {
Subroutine __ANON__: called CC=1 SCAR=0.0
Subroutine __ANON__: called CC=1 SCAR=0.0
Subroutine __ANON__: called CC=1 SCAR=0.0
Subroutine __ANON__: called CC=1 SCAR=0.0
Subroutine __ANON__: called CC=1 SCAR=0.0
Subroutine __ANON__: called CC=1 SCAR=0.0
Subroutine __ANON__: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
48 has tag => (is => "ro", isa => Str);
49 has values => (is => "ro", isa => ArrayRef);
50  
51 sub _equality {
52 my ($type, $x, $y) = @_;
53  
54 return 0 unless ref($x) && (ref($x) // '') eq (ref($y) // '');
55 return 0 unless $x->tag eq $y->tag;
56 return List::Util::all { $_ } List::MoreUtils::pairwise { $type eq '==' ? $a == $b : $a eq $b } @{$x->values}, @{$y->values};
57 }
58  
59 sub _equality_num { return _equality('==', @_); }
60 sub _equality_str { return _equality('eq', @_); }
61  
62 sub _stringify {
63 my $v = shift;
64 return $v->tag . "(" . join(", ", map { "$_" } @{ $v->values }) . ")";
65 }
66  
67 use overload
68 '==' => sub { _equality('==', @_) },
69 '!=' => sub { ! _equality('==', @_) },
70 'eq' => sub { _equality('eq', @_) },
71 'ne' => sub { ! _equality('eq', @_) },
72 '""' => \&_stringify;
73 }
74  
75 sub _apply_pattern {
76 my ($value, $pattern) = @_;
77  
78 if ($pattern->{type} eq 'variable') {
79 return (1, [$value]);
80 }
81  
82 return 0 unless $value && blessed($value) && $value->isa('Types::Algebraic::ADT');
83  
84 return 0 unless $pattern->{constructor} eq $value->tag;
85  
86 my @variables;
87 for my $pair (List::MoreUtils::zip_unflatten(@{$value->values}, @{$pattern->{arguments}})) {
88 my ($rv, $new_vars) = _apply_pattern(@$pair);
89 return 0 unless $rv;
90 push(@variables, @$new_vars);
91 }
92  
93 return (1, \@variables);
94 }
95  
96 keytype ADTConstructor is / (?<tag> (?&PerlIdentifier)) (?<fields> (?: (?&PerlNWS) : (?&PerlIdentifier) )* ) /x;
97  
98 sub _verify_constructor {
99 my ($constructor, $arity) = @_;
100 my $info = $_KNOWN_CONSTRUCTORS{$constructor};
101  
102 confess("Unknown constructor '$constructor'. Pattern matching requires types created through Types::Algebraic.")
103 unless $info;
104  
105 confess("Constructor '$constructor' expects $info->{arg_count} arguments - but is pattern matched with $arity.")
106 unless $info->{arg_count} == $arity;
107  
108 }
109  
110 sub _parse_pattern {
111 my ($pattern) = @_;
112 $pattern =~ m{
113 \A
114 \(
115 (?&PerlOWS)
116 (?<tag>(?&PerlIdentifier))
117 (?<identifiers> (?:(?&PerlNWS) (?&ADTPatternSegment))* )
118 (?&PerlOWS)
119 \)
120 $Types::Algebraic::_TA_REGEX_LIB
121 }xms;
122 my ($tag, $idents) = @+{qw(tag identifiers)};
123  
124 my @segments;
125 my @variables;
126 while ($idents =~ m/(?&PerlNWS) (?<segment>(?&ADTPatternSegment)) $Types::Algebraic::_TA_REGEX_LIB/xmsg) {
127 my $segment = $+{segment};
128  
129 if ($segment =~ m/^\$/) {
130 push(@segments, { type => 'variable', value => $segment });
131 push(@variables, $segment);
132 } elsif ($segment =~ m/^\(/) {
133 my ($parsed, $new_vars) = _parse_pattern($segment);
134 push(@segments, $parsed);
135 push(@variables, @$new_vars);
136 } else {
137 _verify_constructor($segment, 0);
138  
139 push(@segments, { type => 'pattern', constructor => $segment, arguments => [] });
140 }
141 }
142  
143 _verify_constructor($tag, scalar @segments);
144  
145 return ({ type => 'pattern', constructor => $tag, arguments => \@segments }, \@variables);
146 }
147  
148 sub import {
149 Moops->import;
150  
151 Keyword::Simple::define 'match', sub {
152 my ($doc_src) = @_;
153  
154 ($expected, $fail_loc) = ('match statement', 0);
155 my $curly_open = '{';
156  
157 $$doc_src =~ s{
158 \A
159 (?&PerlNWS)
160 (?{ $expected = "parenthesized expression", $fail_loc = pos() })
161 (?<matched_expression> (?&PerlParenthesesList) )
162 (?&PerlNWS)
163 (?{ $expected = "a '$curly_open'", $fail_loc = pos() })
164 \{ (?&PerlOWS)
165  
166 $Types::Algebraic::_TA_REGEX_LIB
167 }{}xms or croak("Invalid match statement.\nExpected: $expected\nFound: ", substr($$doc_src, $fail_loc) =~ /(\S+)/,"\n");
168  
169 my $expr = $+{matched_expression};
170  
171 my $res = "{\n";
172 my $match_body = $expr . "->match(\n";
173  
174 while ($$doc_src =~ m/^(?:with|default)/) {
175 $$doc_src =~ s{
176 \A
177 (?{ $expected = "a with or default statement", $fail_loc = pos() })
178 (?:
179 with (?&PerlNWS)
180 (?{ $expected = "a match pattern", $fail_loc = pos() })
181 (?<with_pattern> (?&ADTPattern))
182 |
183 (?<default> default)
184 ) (?&PerlOWS)
185 (?{ $expected = "a code block", $fail_loc = pos() })
186 (?<block> (?&PerlBlock) ) (?&PerlOWS)
187  
188 $Types::Algebraic::_TA_REGEX_LIB
189 }{}xms or croak("Invalid match statement.\nExpected: $expected\nFound: ", substr($$doc_src, $fail_loc) =~ /(\S+)/,"\n");
190  
191 my ($default, $pattern, $block) = @+{qw(default with_pattern block)};
192  
193 if ($default) {
194 $match_body .= "[ sub { $block; return \$Types::Algebraic::_RETURN_SENTINEL; } ],\n";
195 } else {
196 my ($parsed, $variables) = _parse_pattern($pattern);
197  
198 local $Data::Dumper::Indent = 0;
199 local $Data::Dumper::Terse = 1;
200  
201 my $flattened_pattern = Data::Dumper::Dumper($parsed);
202 my $args = join(',', @$variables);
203  
204 $match_body .= "[$flattened_pattern, sub { my ($args) = \@_; $block; return \$Types::Algebraic::_RETURN_SENTINEL; } ],\n";
205 }
206 }
207 $match_body .= ")";
208  
209 my $curly_close = '}';
210 $$doc_src =~ s{
211 \A
212 (?{ $expected = "a '$curly_close'", $fail_loc = pos() })
213 \}
214  
215 $Types::Algebraic::_TA_REGEX_LIB
216 }{}xms or croak("Invalid match statement.\nExpected: $expected\nFound: ", substr($$doc_src, $fail_loc) =~ /(\S+)/,"\n");
217  
218 $res .= <<"EOF";
219 if (wantarray) {
220 my \@types_algebraic_match_result = $match_body;
221 if (\@types_algebraic_match_result != 1 || \$types_algebraic_match_result[0] != \$Types::Algebraic::_RETURN_SENTINEL) { return \@types_algebraic_match_result };
222 } else {
223 my \$types_algebraic_match_result = $match_body;
224 if (\$types_algebraic_match_result && \$types_algebraic_match_result != \$Types::Algebraic::_RETURN_SENTINEL) { return \$types_algebraic_match_result; }
225 }
226 EOF
227 $res .= "}\n";
228 #say STDERR "\n\n\n$res\n\n-----\n";
229 $$doc_src = $res . $$doc_src;
230 };
231  
232 keyword data (Ident $name, '=', ADTConstructor* @constructors :sep(/\|/)) {
233 my %ARGS;
234 for my $constructor (@constructors) {
235 my $tag = $constructor->{tag};
236  
237 my @args;
238 while ($constructor->{fields} =~ m/ (?&PerlNWS) : (?<ident> (?&PerlIdentifier) ) $PPR::GRAMMAR/xg ) {
239 push(@args, $+{ident});
240 }
241  
242 $ARGS{$tag} = scalar @args;
243  
244 $_KNOWN_CONSTRUCTORS{$tag} = {
245 typename => $name,
246 arg_count => scalar @args,
247 };
248 }
249  
250 my $args_str = join(", ", map { "$_ => $ARGS{$_}" } keys %ARGS);
251  
252 my $res = <<CODE;
253 class $name extends Types::Algebraic::ADT {
254 my %ARGS = ( $args_str );
255 CODE
256  
257 $res .= <<'CODE';
258 sub BUILD {
259 my ($self, $args) = @_;
260 my $tag = $args->{tag} || confess("tag is required - please use public interface");
261 my $values = $args->{values} || confess("values is required - please use public interface");
262  
263 confess("Unknown constructor $tag") unless exists $ARGS{$tag};
264 confess("$tag expects $ARGS{$tag} arguments - given ".scalar @$values) unless @$values == $ARGS{$tag};
265 }
266  
267 sub match {
268 my $self = shift;
269 for my $case (@_) {
270 if (@$case == 2) {
271 my ($pattern, $f) = @$case;
272  
273 my ($matches, $values) = Types::Algebraic::_apply_pattern($self, $pattern);
274 return $f->(@$values) if $matches;
275 }
276 # default
277 if (@$case == 1) {
278 return $case->[0]->(@{ $self->values });
279 }
280 }
281 }
282 }
283 CODE
284  
285 for my $key (keys %ARGS) {
286 $res .= <<CODE;
287 sub $key { return $name->new( tag => '$key', values => [\@_] ); }
288 CODE
289  
290 }
291  
292 #say STDERR $res;
293  
294 return $res;
295 }
296  
297 }
298  
299 sub unimport {
300 unkeyword data;
301 Keyword::Simple::undefine 'match';
302 }
303  
304 1;
305 __END__
↑ Summary