File: Tuple.pm

package info (click to toggle)
libtype-tiny-perl 2.010001-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 4,000 kB
  • sloc: perl: 15,748; makefile: 2; sh: 1
file content (485 lines) | stat: -rw-r--r-- 12,974 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
# INTERNAL MODULE: guts for Tuple type from Types::Standard.

package Types::Standard::Tuple;

use 5.008001;
use strict;
use warnings;

BEGIN {
	$Types::Standard::Tuple::AUTHORITY = 'cpan:TOBYINK';
	$Types::Standard::Tuple::VERSION   = '2.010001';
}

$Types::Standard::Tuple::VERSION =~ tr/_//d;

use Type::Tiny      ();
use Types::Standard ();
use Types::TypeTiny ();

sub _croak ($;@) { require Error::TypeTiny; goto \&Error::TypeTiny::croak }

my $_Optional = Types::Standard::Optional;
my $_Slurpy   = Types::Standard::Slurpy;

use Exporter::Tiny 1.004001 ();
our @ISA = qw( Exporter::Tiny );

sub _exporter_fail {
	my ( $class, $type_name, $values, $globals ) = @_;
	my $caller = $globals->{into};
	
	my @final;
	{
		my $to_type = sub {
			return $_[0] if Types::TypeTiny::is_TypeTiny($_[0]);
			require Type::Utils;
			Type::Utils::dwim_type( $_[0], for => 'caller' );
		};
		my $of = $values->{of};
		Types::TypeTiny::is_ArrayLike($of)
			or _croak( qq{Expected arrayref option "of" for type "$type_name"} );
		@final = map { $to_type->($_) } @$of;
	}
	
	my $type = Types::Standard::Tuple->of( @final );
	$type = $type->create_child_type(
		name => $type_name,
		$type->has_coercion ? ( coercion => 1 ) : (),
		exists( $values->{where} ) ? ( constraint => $values->{where} ) : (),
	);
	
	$INC{'Type/Registry.pm'}
		? 'Type::Registry'->for_class( $caller )->add_type( $type, $type_name )
		: ( $Type::Registry::DELAYED{$caller}{$type_name} = $type )
		unless( ref($caller) or $caller eq '-lexical' or $globals->{'lexical'} );
	return map +( $_->{name} => $_->{code} ), @{ $type->exportables };
}

no warnings;

sub __constraint_generator {
	my $slurpy =
		@_
		&& Types::TypeTiny::is_TypeTiny( $_[-1] )
		&& $_[-1]->is_strictly_a_type_of( $_Slurpy )
		? pop
		: undef;
		
	my @constraints = @_;
	for ( @constraints ) {
		Types::TypeTiny::is_TypeTiny( $_ )
			or
			_croak( "Parameters to Tuple[...] expected to be type constraints; got $_" );
	}
	
	# By god, the Type::Tiny::XS API is currently horrible
	my @xsub;
	if ( Type::Tiny::_USE_XS and !$slurpy ) {
		my @known = map {
			my $known;
			$known = Type::Tiny::XS::is_known( $_->compiled_check )
				unless $_->is_strictly_a_type_of( $_Optional );
			defined( $known ) ? $known : ();
		} @constraints;
		
		if ( @known == @constraints ) {
			my $xsub = Type::Tiny::XS::get_coderef_for(
				sprintf( "Tuple[%s]", join( ',', @known ) ) );
			push @xsub, $xsub if $xsub;
		}
	} #/ if ( Type::Tiny::_USE_XS...)
	
	my @is_optional = map !!$_->is_strictly_a_type_of( $_Optional ), @constraints;
	my $slurp_hash  = $slurpy && $slurpy->my_slurp_into eq 'HASH';
	my $slurp_any   = $slurpy && $slurpy->my_unslurpy->equals( Types::Standard::Any );
	
	my @sorted_is_optional = sort @is_optional;
	join( "|", @sorted_is_optional ) eq join( "|", @is_optional )
		or _croak(
		"Optional parameters to Tuple[...] cannot precede required parameters" );
		
	sub {
		my $value = $_[0];
		if ( $#constraints < $#$value ) {
			return !!0 unless $slurpy;
			my $tmp;
			if ( $slurp_hash ) {
				( $#$value - $#constraints + 1 ) % 2 or return;
				$tmp = +{ @$value[ $#constraints + 1 .. $#$value ] };
				$slurpy->check( $tmp ) or return;
			}
			elsif ( not $slurp_any ) {
				$tmp = +[ @$value[ $#constraints + 1 .. $#$value ] ];
				$slurpy->check( $tmp ) or return;
			}
		} #/ if ( $#constraints < $#$value)
		for my $i ( 0 .. $#constraints ) {
			( $i > $#$value )
				and return !!$is_optional[$i];
				
			$constraints[$i]->check( $value->[$i] )
				or return !!0;
		}
		return !!1;
	}, @xsub;
} #/ sub __constraint_generator

sub __inline_generator {
	my $slurpy =
		@_
		&& Types::TypeTiny::is_TypeTiny( $_[-1] )
		&& $_[-1]->is_strictly_a_type_of( $_Slurpy )
		? pop
		: undef;
	my @constraints = @_;
	
	return if grep { not $_->can_be_inlined } @constraints;
	return if defined $slurpy && !$slurpy->can_be_inlined;
	
	my $xsubname;
	if ( Type::Tiny::_USE_XS and !$slurpy ) {
		my @known = map {
			my $known;
			$known = Type::Tiny::XS::is_known( $_->compiled_check )
				unless $_->is_strictly_a_type_of( $_Optional );
			defined( $known ) ? $known : ();
		} @constraints;
		
		if ( @known == @constraints ) {
			$xsubname = Type::Tiny::XS::get_subname_for(
				sprintf( "Tuple[%s]", join( ',', @known ) ) );
		}
	} #/ if ( Type::Tiny::_USE_XS...)
	
	my $tmpl = "do { my \$tmp = +[\@{%s}[%d..\$#{%s}]]; %s }";
	my $slurpy_any;
	if ( defined $slurpy ) {
		$tmpl =
			'do { my ($orig, $from, $to) = (%s, %d, $#{%s});'
			. '(($to-$from) %% 2) and do { my $tmp = +{@{$orig}[$from..$to]}; %s }'
			. '}'
			if $slurpy->my_slurp_into eq 'HASH';
		$slurpy_any = 1
			if $slurpy->my_unslurpy->equals( Types::Standard::Any );
	}
	
	my @is_optional = map !!$_->is_strictly_a_type_of( $_Optional ), @constraints;
	my $min = 0+ grep !$_, @is_optional;
	
	return sub {
		my $v = $_[1];
		return "$xsubname\($v\)" if $xsubname && !$Type::Tiny::AvoidCallbacks;
		join " and ",
			Types::Standard::ArrayRef->inline_check( $v ),
			(
			( scalar @constraints == $min and not $slurpy )
			? "\@{$v} == $min"
			: sprintf(
				"(\@{$v} == $min or (\@{$v} > $min and \@{$v} <= ${\(1+$#constraints)}) or (\@{$v} > ${\(1+$#constraints)} and %s))",
				(
					$slurpy_any ? '!!1'
					: (
						$slurpy
						? sprintf( $tmpl, $v, $#constraints + 1, $v, $slurpy->inline_check( '$tmp' ) )
						: sprintf( "\@{$v} <= %d", scalar @constraints )
					)
				),
			)
			),
			map {
			my $inline = $constraints[$_]->inline_check( "$v\->[$_]" );
			$inline eq '(!!1)' ? ()
				: (
				$is_optional[$_] ? sprintf( '(@{%s} <= %d or %s)', $v, $_, $inline )
				: $inline
				);
			} 0 .. $#constraints;
	};
} #/ sub __inline_generator

sub __deep_explanation {
	my ( $type, $value, $varname ) = @_;
	
	my @constraints = @{ $type->parameters };
	my $slurpy =
		@constraints
		&& Types::TypeTiny::is_TypeTiny( $constraints[-1] )
		&& $constraints[-1]->is_strictly_a_type_of( $_Slurpy )
		? pop( @constraints )
		: undef;
	@constraints = map Types::TypeTiny::to_TypeTiny( $_ ), @constraints;
	
	if ( @constraints < @$value and not $slurpy ) {
		return [
			sprintf(
				'"%s" expects at most %d values in the array', $type, scalar( @constraints )
			),
			sprintf( '%d values found; too many', scalar( @$value ) ),
		];
	}
	
	for my $i ( 0 .. $#constraints ) {
		next
			if $constraints[$i]
			->is_strictly_a_type_of( Types::Standard::Optional )
			&& $i > $#$value;
		next if $constraints[$i]->check( $value->[$i] );
		
		return [
			sprintf(
				'"%s" constrains value at index %d of array with "%s"', $type, $i,
				$constraints[$i]
			),
			@{
				$constraints[$i]
					->validate_explain( $value->[$i], sprintf( '%s->[%s]', $varname, $i ) )
			},
		];
	} #/ for my $i ( 0 .. $#constraints)
	
	if ( defined( $slurpy ) ) {
		my $tmp =
			$slurpy->my_slurp_into eq 'HASH'
			? +{ @$value[ $#constraints + 1 .. $#$value ] }
			: +[ @$value[ $#constraints + 1 .. $#$value ] ];
		$slurpy->check( $tmp )
			or return [
			sprintf(
				'Array elements from index %d are slurped into a %s which is constrained with "%s"',
				$#constraints + 1,
				( $slurpy->my_slurp_into eq 'HASH' ) ? 'hashref' : 'arrayref',
				( $slurpy->my_unslurpy || $slurpy ),
			),
			@{ ( $slurpy->my_unslurpy || $slurpy )->validate_explain( $tmp, '$SLURPY' ) },
			];
	} #/ if ( defined( $slurpy ...))
	
	# This should never happen...
	return;    # uncoverable statement
} #/ sub __deep_explanation

my $label_counter = 0;

sub __coercion_generator {
	my ( $parent, $child, @tuple ) = @_;
	
	my $slurpy =
		@tuple
		&& Types::TypeTiny::is_TypeTiny( $tuple[-1] )
		&& $tuple[-1]->is_strictly_a_type_of( $_Slurpy )
		? pop( @tuple )
		: undef;
	
	my $child_coercions_exist = 0;
	my $all_inlinable         = 1;
	for my $tc ( @tuple, ( $slurpy ? $slurpy : () ) ) {
		$all_inlinable = 0 if !$tc->can_be_inlined;
		$all_inlinable = 0 if $tc->has_coercion && !$tc->coercion->can_be_inlined;
		$child_coercions_exist++ if $tc->has_coercion;
	}
	
	return unless $child_coercions_exist;
	my $C = "Type::Coercion"->new( type_constraint => $child );
	
	my $slurpy_is_hashref = $slurpy && $slurpy->my_slurp_into eq 'HASH';
		
	if ( $all_inlinable ) {
		$C->add_type_coercions(
			$parent => Types::Standard::Stringable {
				my $label = sprintf( "TUPLELABEL%d", ++$label_counter );
				my @code;
				push @code, 'do { my ($orig, $return_orig, $tmp, @new) = ($_, 0);';
				push @code, "$label: {";
				push @code,
					sprintf(
					'(($return_orig = 1), last %s) if @$orig > %d;', $label,
					scalar @tuple
					) unless $slurpy;
				for my $i ( 0 .. $#tuple ) {
					my $ct          = $tuple[$i];
					my $ct_coerce   = $ct->has_coercion;
					my $ct_optional = $ct->is_a_type_of( Types::Standard::Optional );
					
					push @code, sprintf(
						'if (@$orig > %d) { $tmp = %s; (%s) ? ($new[%d]=$tmp) : (($return_orig=1), last %s) }',
						$i,
						$ct_coerce
						? $ct->coercion->inline_coercion( "\$orig->[$i]" )
						: "\$orig->[$i]",
						$ct->inline_check( '$tmp' ),
						$i,
						$label,
					);
				} #/ for my $i ( 0 .. $#tuple)
				if ( $slurpy ) {
					my $size = @tuple;
					push @code, sprintf( 'if (@$orig > %d) {', $size );
					push @code, sprintf(
						(
							$slurpy_is_hashref
							? 'my $tail = do { no warnings; +{ @{$orig}[%d .. $#$orig]} };'
							: 'my $tail = [ @{$orig}[%d .. $#$orig] ];'
						),
						$size,
					);
					push @code,
						$slurpy->has_coercion
						? sprintf(
						'$tail = %s;',
						$slurpy->coercion->inline_coercion( '$tail' )
						)
						: q();
					push @code, sprintf(
						'(%s) ? push(@new, %s$tail) : ($return_orig++);',
						$slurpy->inline_check( '$tail' ),
						( $slurpy_is_hashref ? '%' : '@' ),
					);
					push @code, '}';
				} #/ if ( $slurpy )
				push @code, '}';
				push @code, '$return_orig ? $orig : \\@new';
				push @code, '}';
				"@code";
			}
		);
	} #/ if ( $all_inlinable )
	
	else {
		my @is_optional = map !!$_->is_strictly_a_type_of( $_Optional ), @tuple;
		
		$C->add_type_coercions(
			$parent => sub {
				my $value = @_ ? $_[0] : $_;
				
				if ( !$slurpy and @$value > @tuple ) {
					return $value;
				}
				
				my @new;
				for my $i ( 0 .. $#tuple ) {
					return \@new if $i > $#$value and $is_optional[$i];
					
					my $ct = $tuple[$i];
					my $x  = $ct->has_coercion ? $ct->coerce( $value->[$i] ) : $value->[$i];
					
					return $value unless $ct->check( $x );
					
					$new[$i] = $x;
				} #/ for my $i ( 0 .. $#tuple)
				
				if ( $slurpy and @$value > @tuple ) {
					no warnings;
					my $tmp =
						$slurpy_is_hashref
						? { @{$value}[ @tuple .. $#$value ] }
						: [ @{$value}[ @tuple .. $#$value ] ];
					$tmp = $slurpy->coerce( $tmp ) if $slurpy->has_coercion;
					$slurpy->check( $tmp )
						? push( @new, $slurpy_is_hashref ? %$tmp : @$tmp )
						: return ( $value );
				} #/ if ( $slurpy and @$value...)
				
				return \@new;
			},
		);
	} #/ else [ if ( $all_inlinable ) ]
	
	return $C;
} #/ sub __coercion_generator

1;

__END__

=pod

=encoding utf-8

=head1 NAME

Types::Standard::Tuple - exporter utility for the B<Tuple> type constraint

=head1 SYNOPSIS

  use Types::Standard -types;
  
  # Normal way to validate a pair of integers.
  #
  Tuple->of( Int, Int )->assert_valid( [ 7, 49 ] );
  
  use Types::Standard::Tuple IntPair => { of => [ Int, Int ] },
  
  # Exported shortcut
  #
  assert_IntPair [ 7, 49 ];

=head1 STATUS

This module is not covered by the
L<Type-Tiny stability policy|Type::Tiny::Manual::Policies/"STABILITY">.

=head1 DESCRIPTION

This is mostly internal code, but can also act as an exporter utility.

=head2 Exports

Types::Standard::Tuple can be used experimentally as an exporter.

  use Types::Standard 'Int';
  use Types::Standard::Tuple IntPair => { of => [ Int, Int ] };

This will export the following functions into your namespace:

=over

=item C<< IntPair >>

=item C<< is_IntPair( $value ) >>

=item C<< assert_IntPair( $value ) >>

=item C<< to_IntPair( $value ) >>

=back

Multiple types can be exported at once:

  use Types::Standard -types;
  use Types::Standard::HashRef (
    IntPair  => { of => [ Int, Int ] },
    StrInt   => { of => [ Str, Int ] },
  );
  
  assert_StrInt [ two => 2 ];   # should not die

It's possible to further constrain the tuple using C<where>:

  use Types::Standard::Tuple MyThing => { of => [ ... ], where => sub { ... } };

=head1 BUGS

Please report any bugs to
L<https://github.com/tobyink/p5-type-tiny/issues>.

=head1 SEE ALSO

L<Types::Standard>.

=head1 AUTHOR

Toby Inkster E<lt>tobyink@cpan.orgE<gt>.

=head1 COPYRIGHT AND LICENCE

This software is copyright (c) 2013-2025 by Toby Inkster.

This is free software; you can redistribute it and/or modify it under
the same terms as the Perl 5 programming language system itself.

=head1 DISCLAIMER OF WARRANTIES

THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED
WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.