blib/lib/Salvation/TC.pm

filter: Statementstmt 81.1% 155 / 191 Branchbran 69.6% 39 / 56 Conditioncond 51.3% 39 / 76 MC/DCmcdc 10.4% 5 / 48 Subroutinesub 93.3% 42 / 45 Podpod 100% 25 / 25 totaltotal 69.1% 305 / 441 SCAR 49.3
CC
60
Cov
72%
create_error_message
56.0
materialize_type
20.8
assert
20.0
CRAP 137.9
↑ Summary blib/lib/Salvation/TC/Parser/PP.pm »
1 package Salvation::TC;
2  
3 =head1 NAME
4  
5 Salvation::TC - Type Constraint, система проверки типов значений.
6  
7 =head1 SYNOPSIS
8  
9 Salvation::TC -> is( 'asd', 'Str' );
10 Salvation::TC -> is( 123, 'Int' );
11 Salvation::TC -> is( 123.45, 'Num' );
12 Salvation::TC -> is( [], 'ArrayRef' );
13 Salvation::TC -> is( [ 1, 2, "asd" ], 'ArrayRef[Int|Str]' );
14  
15 Salvation::TC -> assert( [ { a => undef, b => 1 } ], 'ArrayRef[HashRef[Maybe[Int]]]' );
16 Salvation::TC -> assert( DBScheme::Image -> search_one([]), 'DBScheme' );
17  
18 Salvation::TC -> assert( { asd => 1 }, 'HashRef(Int :asd!, ArrayRef[Int] :list)' ); # OK
19 Salvation::TC -> assert( { asd => 1, list => [ 2 ] }, 'HashRef(Int :asd!, ArrayRef[Int] :list)' ); # OK
20 Salvation::TC -> assert( { qwe => 1 }, 'HashRef(Int :asd!, ArrayRef[Int] :list)' ); # FAIL
21  
22 Salvation::TC -> assert( [ { asd => [], qwe => 1 } ], 'ArrayRef[HashRef(Int :qwe!)](HashRef(ArrayRef :asd!) el)' ); # OK
23  
24 =head1 SEE ALSO
25  
26 L<Moose::Manual::Types>
27  
28 http://perlcabal.org/syn/S06.html#Signatures
29  
30 =cut
31  
32 4 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
33 4 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
34 4 ▶use boolean;
Subroutine BEGIN: called CC=1 SCAR=0.0
35  
36 4 ▶use Carp 'confess';
Subroutine BEGIN: called CC=1 SCAR=0.0
37 4 ▶use Module::Load ();
Subroutine BEGIN: called CC=1 SCAR=0.0
38 4 ▶use Scalar::Util 'blessed';
Subroutine BEGIN: called CC=1 SCAR=0.0
39 4 ▶use Class::Inspector ();
Subroutine BEGIN: called CC=1 SCAR=0.0
40 4 ▶use Devel::PartialDump ();
Subroutine BEGIN: called CC=1 SCAR=0.0
41  
42 4 ▶use Salvation::TC::Parser ();
Subroutine BEGIN: called CC=1 SCAR=0.0
43 4 ▶use Salvation::TC::Meta::Type ();
Subroutine BEGIN: called CC=1 SCAR=0.0
44 4 ▶use Salvation::TC::Meta::Type::Maybe ();
Subroutine BEGIN: called CC=1 SCAR=0.0
45 4 ▶use Salvation::TC::Meta::Type::Union ();
Subroutine BEGIN: called CC=1 SCAR=0.0
46 4 ▶use Salvation::TC::Exception::WrongType ();
Subroutine BEGIN: called CC=1 SCAR=0.0
47  
48 4 our $VERSION = 0.07;
49  
50  
51 =head1 METHODS
52  
53 =cut
54  
55 =head2 init_regular_cases()
56  
57 Инициализирует и кэширует самые частые кейсы.
58  
59 =cut
60  
61 sub init_regular_cases {
62  
63 4 ▶ my ( $self ) = @_;
Subroutine init_regular_cases: called CC=3 SCAR=11.0
Pod documented
64  
65 4 my %table = (
66 Int => 'Number::Integer',
67 Num => 'Number::Float',
68 );
69  
70 4 ▶ while( my ( $alias, $type ) = each( %table ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (() = each %table) 8 4 12
71  
72 8 $type = $self -> get( $type );
73  
74 8 $self -> setup_type( $alias,
75 validator => $type -> validator(),
76 signed_type_generator => $type -> signed_type_generator(),
77 length_type_generator => $type -> length_type_generator(),
78 );
79 }
80  
81 4 foreach my $type (
82 'Any',
83 'ArrayRef',
84 'Bool',
85 'CodeRef',
86 'Date::Reverse',
87 'Date',
88 'Defined',
89 'HashRef',
90 'Object',
91 'Ref',
92 'SessionId',
93 'Str',
94 'Text::English',
95 'Text',
96 'Time',
97 'Undef',
98 'ScalarRef',
99 ) {
100  
101 68 $self -> get( $type );
102 }
103  
104 4 return;
105 }
106  
107 {
108 4 my $table = undef;
109  
110 =head2 get_known_types()
111  
112 Возвращает таблицу известных базовых валидаторов и генератором для них.
113  
114 =cut
115  
116 sub get_known_types {
117  
118 77 ▶ my ( $self ) = @_;
Subroutine get_known_types: called CC=2 SCAR=6.9
Pod documented
119  
120 return $table //= [
121 [ 'Salvation::TC::Type' => {
122 validator => sub {
123 76 ▶ $self -> gen_salvation_tc_type_validator( @_ );
Subroutine __ANON__: called CC=1 SCAR=0.0
124 },
125 signed_type_generator => sub {
126 76 ▶ $self -> gen_salvation_tc_type_signer( @_ );
Subroutine __ANON__: called CC=1 SCAR=0.0
127 },
128 length_type_generator => sub {
129 76 ▶ $self -> gen_salvation_tc_type_length_check( @_ );
Subroutine __ANON__: called CC=1 SCAR=0.0
130 }
131 77 ▶ } ],
Condition100%2/2
$table //= [["Salvation::TC::Type", {"validator", sub { $self->gen_salvation_tc_type_validator(@_); } , "signed_type_generator", sub { $self->gen_salvation_tc_type_signer(@_); } , "length_type_generator", sub { $self->gen_salvation_tc_type_length_check(@_); } }]]
l!l
734
MC/DC100%1/1
$table //= [["Salvation::TC::Type", {"validator", sub { $self->gen_salvation_tc_type_validator(@_); } , "signed_type_generator", sub { $self->gen_salvation_tc_type_signer(@_); } , "length_type_generator", sub { $self->gen_salvation_tc_type_length_check(@_); } }]]
$table
Truth table100%2/2
A
A= $table
Aresult
11
00
132 ];
133 }
134 }
135  
136 =head2 gen_salvation_tc_type_validator( Str $class )
137  
138 Генератор валидаторов значений на основе L<Salvation::TC::Type>.
139  
140 Возвращает CodeRef, являющийся валидатором, соответствующий следующей сигнатуре:
141  
142 ( Any $value )
143  
144 , где:
145  
146 =over
147  
148 =item $value
149  
150 Валидируемое значение.
151  
152 Обязательный параметр.
153  
154 =back
155  
156 Если значение не подходит - валидатор бросает исключение
157 L<Salvation::TC::Exception::WrongType>.
158  
159 Описание аргументов:
160  
161 =over
162  
163 =item $class
164  
165 Имя класса типа.
166  
167 Обязательный параметр.
168  
169 =back
170  
171 =cut
172  
173 4 sub gen_salvation_tc_type_validator {
174  
175 76 ▶ my ( $self, $class ) = @_;
Subroutine gen_salvation_tc_type_validator: called CC=1 SCAR=0.0
Pod documented
176  
177 return sub {
178  
179 264 ▶ $class -> Check( $_[ 0 ] );
Subroutine __ANON__: called CC=1 SCAR=0.0
180 76 };
181 }
182  
183 =head2 gen_salvation_tc_type_signer( Str $class )
184  
185 Генератор валидаторов значений на основе подписанных L<Salvation::TC::Type>.
186  
187 Возвращает CodeRef, являющийся валидатором, соответствующий следующей сигнатуре:
188  
189 ( Any $value )
190  
191 , где:
192  
193 =over
194  
195 =item $value
196  
197 Валидируемое значение.
198  
199 Обязательный параметр.
200  
201 =back
202  
203 Если значение не подходит - валидатор бросает исключение
204 L<Salvation::TC::Exception::WrongType>.
205  
206 Описание аргументов:
207  
208 =over
209  
210 =item $class
211  
212 Имя класса типа.
213  
214 Обязательный параметр.
215  
216 =back
217  
218 =cut
219  
220 sub gen_salvation_tc_type_signer {
221  
222 76 ▶ my ( $self, $class ) = @_;
Subroutine gen_salvation_tc_type_signer: called CC=2 SCAR=6.9
Pod documented
223  
224 76 ▶ return undef unless( $class -> can( 'create_validator_from_sig' ) );
Branch: 1 branch
BranchTrueFalseTotal
unless $class->can("create_validator_from_sig") 68 8 76
225  
226 return sub {
227  
228 12 ▶ $class -> create_validator_from_sig( $_[ 0 ] );
Subroutine __ANON__: called CC=1 SCAR=0.0
229 8 };
230 }
231  
232 =head2 gen_salvation_tc_type_length_check( Str $class )
233  
234 Генератор валидаторов значений на основе L<Salvation::TC::Type>, ограниченных
235 под длине.
236  
237 Возвращает CodeRef, являющийся валидатором, соответствующий следующей сигнатуре:
238  
239 ( Any $value )
240  
241 , где:
242  
243 =over
244  
245 =item $value
246  
247 Валидируемое значение.
248  
249 Обязательный параметр.
250  
251 =back
252  
253 Если значение не подходит - валидатор бросает исключение
254 L<Salvation::TC::Exception::WrongType>.
255  
256 Описание аргументов:
257  
258 =over
259  
260 =item $class
261  
262 Имя класса типа.
263  
264 Обязательный параметр.
265  
266 =back
267  
268 =cut
269  
270 sub gen_salvation_tc_type_length_check {
271  
272 76 ▶ my ( $self, $class ) = @_;
Subroutine gen_salvation_tc_type_length_check: called CC=2 SCAR=6.9
Pod documented
273  
274 76 ▶ return undef unless( $class -> can( 'create_length_validator' ) );
Branch: 1 branch
BranchTrueFalseTotal
unless $class->can("create_length_validator") 56 20 76
275  
276 return sub {
277  
278 24 ▶ $class -> create_length_validator( @_[ 0, 1 ] );
Subroutine __ANON__: called CC=1 SCAR=0.0
279 20 };
280 }
281  
282 =head2 gen_class_type_validator( Str $class )
283  
284 Генератор валидаторов значений, являющихся экземпярами классов.
285  
286 Возвращает CodeRef, являющийся валидатором, соответствующий следующей сигнатуре:
287  
288 ( Any $value )
289  
290 , где:
291  
292 =over
293  
294 =item $value
295  
296 Валидируемое значение.
297  
298 Обязательный параметр.
299  
300 =back
301  
302 Если значение не подходит - валидатор бросает исключение
303 L<Salvation::TC::Exception::WrongType>.
304  
305 Описание аргументов:
306  
307 =over
308  
309 =item $class
310  
311 Имя класса типа.
312  
313 Обязательный параметр.
314  
315 =back
316  
317 =cut
318  
319 sub gen_class_type_validator {
320  
321 1 ▶ my ( $self, $class ) = @_;
Subroutine gen_class_type_validator: called CC=1 SCAR=0.1
Pod documented
322  
323 return sub {
324  
325 8 ▶ ( defined $_[ 0 ] && blessed $_[ 0 ] && $_[ 0 ] -> isa( $class ) )
Subroutine __ANON__: called CC=4 SCAR=14.3
Branch: 1 branch
BranchTrueFalseTotal
defined $_[0] and builtin::blessed($_[0]) and $_[0]->isa($class) or "Salvation::TC::Exception::WrongType"->throw("type", $class, "value", $_[0]) 7 1 8
Condition66%4/6
defined $_[0] and builtin::blessed($_[0]) and $_[0]->isa($class)
!ll&&!rl&&r
701
defined $_[0] and builtin::blessed($_[0])
!ll&&!rl&&r
071
MC/DC33%1/3
defined $_[0] and builtin::blessed($_[0]) and $_[0]->isa($class)
defined $_[0] builtin::blessed($_[0]) $_[0]->isa($class)
Truth table50%2/4
A and B and C
A= defined $_[0]B= builtin::blessed($_[0])C= $_[0]->isa($class)
ABCresult
0XX0
10X0
1100
1111
326 || Salvation::TC::Exception::WrongType -> throw(
327 type => $class, value => $_[ 0 ]
328 )
329 1 };
330 }
331  
332 {
333 4 my %TYPE;
334  
335 =head2 setup_type( Str $name, @rest )
336  
337 Инициализирует класс для класса типа.
338  
339 Описание аргументов:
340  
341 =over
342  
343 =item $name
344  
345 Имя типа.
346  
347 Обязательный параметр.
348  
349 =item @rest
350  
351 Иные, сопутствующие типу параметры (пары ключ-значение). Основные параметры типа:
352  
353 =over
354  
355 =item validator
356  
357 CodeRef, функция-валидатор.
358  
359 =back
360  
361 =back
362  
363 =cut
364  
365 sub setup_type {
366  
367 122 ▶ my ( $self, $name, @rest ) = @_;
Subroutine setup_type: called CC=3 SCAR=14.2
Pod documented
368  
369 122 ▶ return $TYPE{ ref( $self ) || $self } -> { $name } //= $self -> simple_type_class_name() -> new( @rest, name => $name );
Condition33%2/6
$TYPE{ref $self or $self}{$name} //= $self->simple_type_class_name->new(@rest, "name", $name)
l!l&&r!l&&!r
01220
ref $self || $self
l!l&&r!l&&!r
01220
MC/DC0%0/2
$TYPE{ref $self or $self}{$name} //= $self->simple_type_class_name->new(@rest, "name", $name)
$TYPE{ref $self or $self}{$name} $self->simple_type_class_name->new(@rest, "name", $name)
MC/DC0%0/2
ref $self || $self
ref $self $self
Truth table33%1/3
A //= B
A= $TYPE{ref $self or $self}{$name}B= $self->simple_type_class_name->new(@rest, "name", $name)
ABresult
1X1
011
000
Truth table33%1/3
A || B
A= ref $selfB= $self
ABresult
1X1
011
000
370 }
371  
372 =head2 simple_type_class_name()
373  
374 =cut
375  
376 sub simple_type_class_name {
377  
378 122 ▶ return 'Salvation::TC::Meta::Type';
Subroutine simple_type_class_name: called CC=1 SCAR=0.0
Pod documented
379 }
380  
381 =head2 setup_maybe_type( Str $name, @rest )
382  
383 =cut
384  
385 sub setup_maybe_type {
386  
387 1 ▶ my ( $self, $name, @rest ) = @_;
Subroutine setup_maybe_type: called CC=3 SCAR=14.2
Pod documented
388  
389 1 ▶ return $TYPE{ ref( $self ) || $self } -> { $name } //= $self -> maybe_type_class_name() -> new( @rest, name => $name );
Condition33%2/6
$TYPE{ref $self or $self}{$name} //= $self->maybe_type_class_name->new(@rest, "name", $name)
l!l&&r!l&&!r
010
ref $self || $self
l!l&&r!l&&!r
010
MC/DC0%0/2
$TYPE{ref $self or $self}{$name} //= $self->maybe_type_class_name->new(@rest, "name", $name)
$TYPE{ref $self or $self}{$name} $self->maybe_type_class_name->new(@rest, "name", $name)
MC/DC0%0/2
ref $self || $self
ref $self $self
Truth table33%1/3
A //= B
A= $TYPE{ref $self or $self}{$name}B= $self->maybe_type_class_name->new(@rest, "name", $name)
ABresult
1X1
011
000
Truth table33%1/3
A || B
A= ref $selfB= $self
ABresult
1X1
011
000
390 }
391  
392 =head2 maybe_type_class_name()
393  
394 =cut
395  
396 sub maybe_type_class_name {
397  
398 1 ▶ return 'Salvation::TC::Meta::Type::Maybe';
Subroutine maybe_type_class_name: called CC=1 SCAR=0.0
Pod documented
399 }
400  
401 =head2 setup_union_type( Str $name, @rest )
402  
403 =cut
404  
405 sub setup_union_type {
406  
407 9 ▶ my ( $self, $name, @rest ) = @_;
Subroutine setup_union_type: called CC=3 SCAR=14.2
Pod documented
408  
409 9 ▶ return $TYPE{ ref( $self ) || $self } -> { $name } //= $self -> union_type_class_name() -> new( @rest, name => $name );
Condition33%2/6
$TYPE{ref $self or $self}{$name} //= $self->union_type_class_name->new(@rest, "name", $name)
l!l&&r!l&&!r
090
ref $self || $self
l!l&&r!l&&!r
090
MC/DC0%0/2
$TYPE{ref $self or $self}{$name} //= $self->union_type_class_name->new(@rest, "name", $name)
$TYPE{ref $self or $self}{$name} $self->union_type_class_name->new(@rest, "name", $name)
MC/DC0%0/2
ref $self || $self
ref $self $self
Truth table33%1/3
A //= B
A= $TYPE{ref $self or $self}{$name}B= $self->union_type_class_name->new(@rest, "name", $name)
ABresult
1X1
011
000
Truth table33%1/3
A || B
A= ref $selfB= $self
ABresult
1X1
011
000
410 }
411  
412 =head2 union_type_class_name()
413  
414 =cut
415  
416 sub union_type_class_name {
417  
418 9 ▶ return 'Salvation::TC::Meta::Type::Union';
Subroutine union_type_class_name: called CC=1 SCAR=0.0
Pod documented
419 }
420  
421 =head2 setup_parameterized_type( Str $name, Str $class, @rest )
422  
423 =cut
424  
425 sub setup_parameterized_type {
426  
427 46 ▶ my ( $self, $name, $class, @rest ) = @_;
Subroutine setup_parameterized_type: called CC=3 SCAR=14.2
Pod documented
428  
429 46 ▶ return $TYPE{ ref( $self ) || $self } -> { $name } //= $class -> new( @rest, name => $name );
Condition33%2/6
$TYPE{ref $self or $self}{$name} //= $class->new(@rest, "name", $name)
l!l&&r!l&&!r
0460
ref $self || $self
l!l&&r!l&&!r
0460
MC/DC0%0/2
$TYPE{ref $self or $self}{$name} //= $class->new(@rest, "name", $name)
$TYPE{ref $self or $self}{$name} $class->new(@rest, "name", $name)
MC/DC0%0/2
ref $self || $self
ref $self $self
Truth table33%1/3
A //= B
A= $TYPE{ref $self or $self}{$name}B= $class->new(@rest, "name", $name)
ABresult
1X1
011
000
Truth table33%1/3
A || B
A= ref $selfB= $self
ABresult
1X1
011
000
430 }
431  
432 =head2 get_type( Str $name )
433  
434 Возвращает уже созданный класс для класса типа.
435  
436 Описание аргументов:
437  
438 =over
439  
440 =item $name
441  
442 Имя типа.
443  
444 Обязательный параметр.
445  
446 =back
447  
448 =cut
449  
450 sub get_type {
451  
452 499 ▶ my ( $self, $name ) = @_;
Subroutine get_type: called CC=2 SCAR=8.1
Pod documented
453  
454 499 ▶ return $TYPE{ ref( $self ) || $self } -> { $name };
Condition33%1/3
ref $self || $self
l!l&&r!l&&!r
04990
MC/DC0%0/2
ref $self || $self
ref $self $self
Truth table33%1/3
A || B
A= ref $selfB= $self
ABresult
1X1
011
000
455 }
456 }
457  
458 =head2 get_type_parser()
459  
460 Возвращает имя класса парсера типов.
461  
462 =cut
463  
464 4 sub get_type_parser {
465  
466 137 ▶ return 'Salvation::TC::Parser';
Subroutine get_type_parser: called CC=1 SCAR=0.0
Pod documented
467 }
468  
469 =head2 parse_type( Str $str )
470  
471 Анализирует строку и возвращает класс описанного в ней класса типа.
472  
473 Если класс для этого класса типа ещё не был инициализирован - инициализирует
474 его.
475  
476 Описание аргументов:
477  
478 =over
479  
480 =item $str
481  
482 Строка, описывающая тип.
483  
484 Обязательный параметр.
485  
486 =back
487  
488 =cut
489  
490 sub parse_type {
491  
492 137 ▶ my ( $self, $str ) = @_;
Subroutine parse_type: called CC=1 SCAR=0.0
Pod documented
493  
494 137 return $self -> materialize_type(
495 $self -> get_type_parser() -> tokenize_type_str( $str, {} )
496 );
497 }
498  
499 =head2 materialize_type( ArrayRef[HashRef] $tokens )
500  
501 Превращает токены �� классы типов.
502  
503 =cut
504  
505 sub materialize_type {
506  
507 315 ▶ my ( $self, $tokens ) = @_;
Subroutine materialize_type: called CC=20 SCAR=30.3
Pod documented
508  
509 315 ▶ if( scalar( @$tokens ) == 1 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @$tokens == 1) { } 306 9 315
510  
511 306 ▶ if( exists $tokens -> [ 0 ] -> { 'type' } ) {
Branch: 5 branches
BranchTrueFalseTotal
if (exists $tokens->[0]{'type'}) { } 213 93 306
elsif (exists $tokens->[0]{'maybe'}) { } 2 91 93
elsif (exists $tokens->[0]{'class'}) { } 51 40 91
elsif (exists $tokens->[0]{'signed'}) { } 12 28 40
elsif (exists $tokens->[0]{'length'}) { } 28 0 28
512  
513 213 return $self -> get_or_create_simple_type( $tokens -> [ 0 ] -> { 'type' } );
514  
515 } elsif( exists $tokens -> [ 0 ] -> { 'maybe' } ) {
516  
517 2 my $type = $self -> materialize_type( $tokens -> [ 0 ] -> { 'maybe' } );
518 2 my $name = sprintf( 'Maybe[%s]', $type -> name() );
519  
520 2 ▶ return ( $self -> get_type( $name ) // $self -> setup_maybe_type(
Condition66%2/3
$self->get_type($name) // $self->setup_maybe_type($name, "validator", $type->validator, "base", $type)
l!l&&r!l&&!r
110
MC/DC0%0/2
$self->get_type($name) // $self->setup_maybe_type($name, "validator", $type->validator, "base", $type)
$self->get_type($name) $self->setup_maybe_type($name, "validator", $type->validator, "base", $type)
Truth table66%2/3
A // B
A= $self->get_type($name)B= $self->setup_maybe_type($name, "validator", $type->validator, "base", $type)
ABresult
1X1
011
000
521 $name, validator => $type -> validator(), base => $type,
522 ) );
523  
524 } elsif( exists $tokens -> [ 0 ] -> { 'class' } ) {
525  
526 51 my $base = $self -> materialize_type( $tokens -> [ 0 ] -> { 'base' } );
527 51 my $inner = $self -> materialize_type( $tokens -> [ 0 ] -> { 'param' } );
528 51 my $name = sprintf( '%s[%s]', $base -> name(), $inner -> name() );
529  
530 return ( $self -> get_type( $name ) // $self -> setup_parameterized_type(
531 51 ▶ $name, $tokens -> [ 0 ] -> { 'class' }, base => $base,
Condition66%2/3
$self->get_type($name) // $self->setup_parameterized_type($name, $tokens->[0]{"class"}, "base", $base, "validator", $base->validator, "inner", $inner)
l!l&&r!l&&!r
14370
MC/DC0%0/2
$self->get_type($name) // $self->setup_parameterized_type($name, $tokens->[0]{"class"}, "base", $base, "validator", $base->validator, "inner", $inner)
$self->get_type($name) $self->setup_parameterized_type($name, $tokens->[0]{"class"}, "base", $base, "validator", $base->validator, "inner", $inner)
Truth table66%2/3
A // B
A= $self->get_type($name)B= $self->setup_parameterized_type($name, $tokens->[0]{"class"}, "base", $base, "validator", $base->validator, "inner", $inner)
ABresult
1X1
011
000
532 validator => $base -> validator(), inner => $inner,
533 ) );
534  
535 } elsif( exists $tokens -> [ 0 ] -> { 'signed' } ) {
536  
537 12 my $data = $tokens -> [ 0 ] -> { 'signed' };
538  
539 12 my $type = $self -> materialize_type( [ $data -> { 'type' } ] );
540 12 my $name = sprintf( '%s%s', $type -> name(), $data -> { 'source' } );
541  
542 12 my $present_type = $self -> get_type( $name );
543  
544 12 ▶ return $present_type if( defined $present_type );
Branch: 1 branch
BranchTrueFalseTotal
if defined $present_type 0 12 12
545  
546 12 foreach my $el ( @{ $data -> { 'signature' } } ) {
547  
548 15 $el -> { 'type' } = $self -> materialize_type( $el -> { 'type' } );
549 }
550  
551 12 ▶ my $method = ( $type -> isa( 'Salvation::TC::Meta::Type::Parameterized' )
Branch: 1 branch
BranchTrueFalseTotal
$type->isa('Salvation::TC::Meta::Type::Parameterized') ? : 4 8 12
552 ? 'setup_parameterized_type'
553 : 'setup_type' );
554  
555 return $self -> $method( $name,
556 ( ( $method eq 'setup_parameterized_type' ) ? (
557 ref( $type ),
558 inner => $type -> inner(),
559 ) : () ),
560 validator => $type -> sign( $data -> { 'signature' } ),
561 length_type_generator => $type -> length_type_generator(),
562 12 ▶ signature => $data -> { 'signature' },
Branch: 1 branch
BranchTrueFalseTotal
$method eq 'setup_parameterized_type' ? : 4 8 12
563 base => $type,
564 );
565  
566 } elsif( exists $tokens -> [ 0 ] -> { 'length' } ) {
567  
568 28 my $data = $tokens -> [ 0 ] -> { 'length' };
569  
570 28 my $type = $self -> materialize_type( [ $data -> { 'type' } ] );
571 28 ▶ my $name = sprintf( '%s{%s,%s}', $type -> name(), $data -> { 'min' }, ( $data -> { 'max' } // '' ) );
Condition100%2/2
$data->{"max"} // ""
l!l
217
MC/DC100%1/1
$data->{"max"} // ""
$data->{"max"}
Truth table100%2/2
A
A= $data->{"max"}
Aresult
11
00
572  
573 28 ▶ my $method = ( $type -> isa( 'Salvation::TC::Meta::Type::Parameterized' )
Branch: 1 branch
BranchTrueFalseTotal
$type->isa('Salvation::TC::Meta::Type::Parameterized') ? : 5 23 28
574 ? 'setup_parameterized_type'
575 : 'setup_type' );
576  
577 return ( $self -> get_type( $name ) // $self -> $method( $name,
578 ( ( $method eq 'setup_parameterized_type' ) ? (
579 ref( $type ),
580 inner => $type -> inner(),
581 ) : () ),
582 28 ▶ validator => $type -> length_checker( @$data{ 'min', 'max' } ),
Branch: 2 branches
BranchTrueFalseTotal
$method eq 'setup_parameterized_type' ? : 5 19 24
$type->has_signature ? : 1 23 24
Condition66%2/3
$self->get_type($name) // $self->$method($name, $method eq "setup_parameterized_type" ? (ref $type, "inner", $type->inner) : (), "validator", $type->length_checker(@$data{"min", "max"}), "signed_type_generator", $type->signed_type_generator, $type->has_signature ? ("signature", $type->signature) : (), "base", $type)
l!l&&r!l&&!r
4240
MC/DC0%0/2
$self->get_type($name) // $self->$method($name, $method eq "setup_parameterized_type" ? (ref $type, "inner", $type->inner) : (), "validator", $type->length_checker(@$data{"min", "max"}), "signed_type_generator", $type->signed_type_generator, $type->has_signature ? ("signature", $type->signature) : (), "base", $type)
$self->get_type($name) $self->$method($name, $method eq "setup_parameterized_type" ? (ref $type, "inner", $type->inner) : (), "validator", $type->length_checker(@$data{"min", "max"}), "signed_type_generator", $type->signed_type_generator, $type->has_signature ? ("signature", $type->signature) : (), "base", $type)
Truth table66%2/3
A // B
A= $self->get_type($name)B= $self->$method($name, $method eq "setup_parameterized_type" ? (ref $type, "inner", $type->inner) : (), "validator", $type->length_checker(@$data{"min", "max"}), "signed_type_generator", $type->signed_type_generator, $type->has_signature ? ("signature", $type->signature) : (), "base", $type)
ABresult
1X1
011
000
583 signed_type_generator => $type -> signed_type_generator(),
584 ( $type -> has_signature() ? (
585 signature => $type -> signature(),
586 ) : () ),
587 base => $type,
588 ) );
589  
590 } else {
591  
592 0 require Data::Dumper;
593  
594 0 die( 'Unknown token: ' . Data::Dumper::Dumper( $tokens ) );
595 }
596  
597 } else {
598  
599 9 my @types = ();
600  
601 9 foreach my $token ( @$tokens ) {
602  
603 19 push( @types, $self -> materialize_type( [ $token ] ) );
604 }
605  
606 9 my $name = join( '|', map( { $_ -> name() } @types ) );
607  
608 9 ▶ return ( $self -> get_type( $name ) // $self -> setup_union_type(
Condition33%1/3
$self->get_type($name) // $self->setup_union_type($name, "types", \@types)
l!l&&r!l&&!r
090
MC/DC0%0/2
$self->get_type($name) // $self->setup_union_type($name, "types", \@types)
$self->get_type($name) $self->setup_union_type($name, "types", \@types)
Truth table33%1/3
A // B
A= $self->get_type($name)B= $self->setup_union_type($name, "types", \@types)
ABresult
1X1
011
000
609 $name, types => \@types
610 ) );
611 }
612 }
613  
614 =head2 simple_type_class_ns()
615  
616 =cut
617  
618 sub simple_type_class_ns {
619  
620 213 ▶ return 'Salvation::TC::Type';
Subroutine simple_type_class_ns: called CC=1 SCAR=0.0
Pod documented
621 }
622  
623 =head2 get_or_create_simple_type( Str $str )
624  
625 Возвращает базовый тип с именем C<$str>.
626  
627 =cut
628  
629 sub get_or_create_simple_type {
630  
631 213 ▶ my ( $self, $str ) = @_;
Subroutine get_or_create_simple_type: called CC=10 SCAR=23.2
Pod documented
632  
633 213 my $salvation_tc_type_str = sprintf( '%s::%s', $self -> simple_type_class_ns(), $str );
634  
635 213 ▶ my $type = ( $self -> get_type( $str ) // $self -> get_type( $salvation_tc_type_str ) );
Condition100%3/3
$self->get_type($str) // $self->get_type($salvation_tc_type_str)
l!l&&r!l&&!r
399777
MC/DC100%2/2
$self->get_type($str) // $self->get_type($salvation_tc_type_str)
$self->get_type($str) $self->get_type($salvation_tc_type_str)
Truth table100%3/3
A // B
A= $self->get_type($str)B= $self->get_type($salvation_tc_type_str)
ABresult
1X1
011
000
636  
637 213 ▶ return $type if( defined $type );
Branch: 1 branch
BranchTrueFalseTotal
if defined $type 136 77 213
638  
639 77 ▶ if(
Branch: 1 branch
BranchTrueFalseTotal
if (not "Class::Inspector"->loaded($str) || eval { do { &Module::Load::load($str); 1 } } and "Class::Inspector"->loaded($salvation_tc_type_str) || eval { do { &Module::Load::load($salvation_tc_type_str); 1 } }) 76 1 77
Condition66%4/6
not "Class::Inspector"->loaded($str) || eval { do { &Module::Load::load($str); 1 } } and "Class::Inspector"->loaded($salvation_tc_type_str) || eval { do { &Module::Load::load($salvation_tc_type_str); 1 } }
!ll&&!rl&&r
1076
'Class::Inspector'->loaded($str) || eval { do { &Module::Load::load($str); 1 } }
l!l&&r!l&&!r
1076
MC/DC0%0/3
not "Class::Inspector"->loaded($str) || eval { do { &Module::Load::load($str); 1 } } and "Class::Inspector"->loaded($salvation_tc_type_str) || eval { do { &Module::Load::load($salvation_tc_type_str); 1 } }
'Class::Inspector'->loaded($str) eval { do { &Module::Load::load($str); 1 } } "Class::Inspector"->loaded($salvation_tc_type_str) || eval { do { &Module::Load::load($salvation_tc_type_str); 1 } }
Truth table50%2/4
not(A || B) and C
A= 'Class::Inspector'->loaded($str)B= eval { do { &Module::Load::load($str); 1 } }C= "Class::Inspector"->loaded($salvation_tc_type_str) || eval { do { &Module::Load::load($salvation_tc_type_str); 1 } }
ABCresult
1XX0
01X0
0000
0011
640 ! Class::Inspector -> loaded( $str )
641 76 ▶ && ! eval{ Module::Load::load( $str ); 1 }
Condition66%2/3
"Class::Inspector"->loaded($salvation_tc_type_str) or eval { do { &Module::Load::load($salvation_tc_type_str); 1 } }
l!l&&r!l&&!r
16600
MC/DC0%0/2
"Class::Inspector"->loaded($salvation_tc_type_str) or eval { do { &Module::Load::load($salvation_tc_type_str); 1 } }
"Class::Inspector"->loaded($salvation_tc_type_str) eval { do { &Module::Load::load($salvation_tc_type_str); 1 } }
Truth table66%2/3
A or B
A= "Class::Inspector"->loaded($salvation_tc_type_str)B= eval { do { &Module::Load::load($salvation_tc_type_str); 1 } }
ABresult
1X1
011
000
642 && (
643 Class::Inspector -> loaded( $salvation_tc_type_str )
644 60 || eval{ Module::Load::load( $salvation_tc_type_str ); 1 }
645 )
646 ) {
647  
648 76 $str = $salvation_tc_type_str;
649 }
650  
651 77 my $validator = undef;
652 77 my $signed_type_generator = undef;
653 77 my $length_type_generator = undef;
654  
655 77 foreach my $spec ( @{ $self -> get_known_types() } ) {
656  
657 77 ▶ if( $str -> isa( $spec -> [ 0 ] ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($str->isa($spec->[0])) 76 1 77
658  
659 76 $validator = $spec -> [ 1 ] -> { 'validator' } -> ( $str );
660 76 $signed_type_generator = $spec -> [ 1 ] -> { 'signed_type_generator' } -> ( $str );
661 76 $length_type_generator = $spec -> [ 1 ] -> { 'length_type_generator' } -> ( $str );
662  
663 76 last;
664 }
665 }
666  
667 77 ▶ return $self -> setup_type( $str,
Condition66%2/3
$validator // $self->gen_class_type_validator($str)
l!l&&r!l&&!r
7610
MC/DC0%0/2
$validator // $self->gen_class_type_validator($str)
$validator $self->gen_class_type_validator($str)
Truth table66%2/3
A // B
A= $validatorB= $self->gen_class_type_validator($str)
ABresult
1X1
011
000
668 validator => ( $validator // $self -> gen_class_type_validator( $str ) ),
669 signed_type_generator => $signed_type_generator,
670 length_type_generator => $length_type_generator,
671 );
672 }
673  
674 {
675 4 my %cache = ();
676  
677 =head2 get( Str $constraint )
678  
679 Возвращает объект для типа C<$constraint>.
680  
681 =cut
682  
683 sub get {
684  
685 255 ▶ my ( $self, $constraint ) = @_;
Subroutine get: called CC=3 SCAR=12.5
Pod documented
686  
687 255 ▶ return $cache{ ref( $self ) || $self } -> { $constraint } //= $self -> parse_type( $constraint );
Condition50%3/6
$cache{ref $self or $self}{$constraint} //= $self->parse_type($constraint)
l!l&&r!l&&!r
1181370
ref $self || $self
l!l&&r!l&&!r
02550
MC/DC0%0/2
$cache{ref $self or $self}{$constraint} //= $self->parse_type($constraint)
$cache{ref $self or $self}{$constraint} $self->parse_type($constraint)
MC/DC0%0/2
ref $self || $self
ref $self $self
Truth table66%2/3
A //= B
A= $cache{ref $self or $self}{$constraint}B= $self->parse_type($constraint)
ABresult
1X1
011
000
Truth table33%1/3
A || B
A= ref $selfB= $self
ABresult
1X1
011
000
688 }
689 }
690  
691 =head2 is( Any $value, Str $constraint )
692  
693 Проверяет, является ли C<$value> значением типа C<$constraint>.
694  
695 Возвращает C<true> в случае, если является, иначе - возвращает C<false>.
696  
697 =cut
698  
699 4 sub is {
700  
701 140 ▶ my ( $self, $value, $constraint ) = @_;
Subroutine is: called CC=4 SCAR=14.6
Pod documented
702  
703 140 eval { $self -> get( $constraint ) -> check( $value ) };
704  
705 140 ▶ if( $@ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 86 54 140
706  
707 86 ▶ if( blessed( $@ ) && $@ -> isa( 'Salvation::TC::Exception::WrongType' ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (builtin::blessed($@) and $@->isa('Salvation::TC::Exception::WrongType')) { } 86 0 86
Condition33%1/3
builtin::blessed($@) and $@->isa("Salvation::TC::Exception::WrongType")
!ll&&!rl&&r
0086
MC/DC0%0/2
builtin::blessed($@) and $@->isa("Salvation::TC::Exception::WrongType")
builtin::blessed($@) $@->isa("Salvation::TC::Exception::WrongType")
Truth table33%1/3
A and B
A= builtin::blessed($@)B= $@->isa("Salvation::TC::Exception::WrongType")
ABresult
0X0
100
111
708  
709 86 return false;
710  
711 } else {
712  
713 0 die( $@ );
714 }
715 };
716  
717 54 return true;
718 }
719  
720 =head2 assert( Any $value, Str $constraint )
721  
722 Проверяет, является ли C<$value> значением типа C<$constraint>.
723  
724 Возвращает C<true> в случае, если является, иначе - вызывает C<die>.
725  
726 =cut
727  
728 sub assert {
729  
730 0 ▶ my ( $self, $value, $constraint ) = @_;
Subroutine assert: not called CC=4 SCAR=30.0
Pod documented
731  
732 0 eval { $self -> get( $constraint ) -> check( $value ) };
733  
734 0 ▶ if( $@ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 0 0
735  
736 0 ▶ if( blessed( $@ ) && $@ -> isa( 'Salvation::TC::Exception::WrongType' ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (builtin::blessed($@) and $@->isa('Salvation::TC::Exception::WrongType')) { } 0 0 0
Condition0%0/3
builtin::blessed($@) and $@->isa("Salvation::TC::Exception::WrongType")
!ll&&!rl&&r
000
MC/DC0%0/2
builtin::blessed($@) and $@->isa("Salvation::TC::Exception::WrongType")
builtin::blessed($@) $@->isa("Salvation::TC::Exception::WrongType")
Truth table0%0/3
A and B
A= builtin::blessed($@)B= $@->isa("Salvation::TC::Exception::WrongType")
ABresult
0X0
100
111
737  
738 0 confess( join( "\n", ( $self -> create_error_message( $@ ), '' ) ) );
739  
740 } else {
741  
742 0 die( $@ );
743 }
744 };
745  
746 0 return true;
747 }
748  
749 =head2 create_error_message( Salvation::TC::Exception::WrongType $e )
750  
751 =cut
752  
753 sub create_error_message {
754  
755 0 ▶ my ( $self, $e ) = @_;
Subroutine create_error_message: not called CC=7 SCAR=40.3
Pod documented
756  
757 0 my @stack = ( $e );
758 0 my @lines = ();
759  
760 0 ▶ while( defined( my $node = shift( @stack ) ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $node = shift @stack)) 0 0 0
761  
762 0 ▶ if( $node -> isa( 'Salvation::TC::Exception::WrongType::TC' ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($node->isa('Salvation::TC::Exception::WrongType::TC')) { } 0 0 0
763  
764 0 my $str = '';
765  
766 0 ▶ if( defined( my $param_name = $node -> getParamName() ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $param_name = $node->getParamName)) { } 0 0 0
767  
768 0 $str = sprintf(
769 'Value %s for parameter "%s" does not match type constraint %s',
770 Devel::PartialDump -> new() -> dump( $node -> getValue() ),
771 $param_name, $node -> getType(),
772 );
773  
774 } else {
775  
776 0 $str = sprintf(
777 'Value %s does not match type constraint %s',
778 Devel::PartialDump -> new() -> dump( $node -> getValue() ),
779 $node -> getType(),
780 );
781 }
782  
783  
784 0 ▶ if( defined( my $prev = $node -> getPrev() ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $prev = $node->getPrev)) { } 0 0 0
785  
786 0 push( @lines, "${str} because:" );
787  
788 0 ▶ if( ref( $prev ) eq 'ARRAY' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $prev eq 'ARRAY') { } 0 0 0
789  
790 0 my $i = 0;
791  
792 0 foreach my $e ( @$prev ) {
793  
794 push( @lines,
795 ++$i . ': ',
796 0 map( { "\t$_" } $self -> create_error_message( $e ) )
797 );
798 }
799  
800 } else {
801  
802 0 push( @stack, $prev );
803 }
804  
805 } else {
806  
807 0 push( @lines, $str );
808 }
809  
810 } else {
811  
812 0 push( @lines, sprintf(
813 'Value %s does not match type constraint %s',
814 Devel::PartialDump -> new() -> dump( $node -> getValue() ),
815 $node -> getType(),
816 ) );
817 }
818 }
819  
820 0 return @lines;
821 }
822  
823 =head2 coerce( Any $value, Str $constraint )
824  
825 Пытается привести значение C<$value> к значению типа C<$constraint>.
826  
827 Если приведение прошло успешно - возвращает изменённое значение, иначе -
828 возвращает C<$value> без изменения*.
829  
830 * Для совместимости с API Moose.
831  
832 =cut
833  
834 sub coerce {
835  
836 8 ▶ my ( $self, $value, $constraint ) = @_;
Subroutine coerce: called CC=1 SCAR=0.0
Pod documented
837  
838 8 return $self -> get( $constraint ) -> coerce( $value );
839 }
840  
841 =head2 ensure( Any $value, Str $constraint )
842  
843 Пытается привести значение C<$value> к значению типа C<$constraint>.
844  
845 Если приведение прошло успешно - возвращает изменённое значение, иначе -
846 вызывает C<die>.
847  
848 =cut
849  
850 sub ensure {
851  
852 0 ▶ my ( $self, $value, $constraint ) = @_;
Subroutine ensure: not called CC=1 SCAR=6.9
Pod documented
853  
854 0 $value = $self -> coerce( $value, $constraint );
855  
856 0 $self -> assert( $value, $constraint );
857  
858 0 return $value;
859 }
860  
861 4 __PACKAGE__ -> init_regular_cases();
862  
863 4 1;
864  
865 __END__
↑ Summary blib/lib/Salvation/TC/Parser/PP.pm »