Skip to content

Commit

Permalink
overloaded operators now throw exception if given undef argument - #519
Browse files Browse the repository at this point in the history
  • Loading branch information
mohawk2 committed Jan 10, 2025
1 parent 5b5499a commit 6c692eb
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 7 deletions.
1 change: 1 addition & 0 deletions Changes
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
- InplaceDoc now automatically generated like BadDoc, Signature doc includes types
- Overload key added to PP (#519)
- "usage" section of xform docs now automatically generated (#519)
- overloaded operators now throw exception if given undef argument (#519) - thanks @cgtinney for report

2.098 2025-01-03
- fix Windows build problems
Expand Down
24 changes: 17 additions & 7 deletions lib/PDL/PP.pm
Original file line number Diff line number Diff line change
Expand Up @@ -1441,25 +1441,35 @@ $PDL::PP::deftbl =
my $fullname = $::PDLOBJ."::$name";
if ($one_arg) {
$ret .= pp_line_numbers(__LINE__, <<EOF);
use overload '$op' => sub { $fullname(\$_[0]) };
use overload '$op' => sub {
Carp::confess("$fullname: overloaded '$op' given undef")
if grep !defined, \$_[0];
$fullname(\$_[0]);
};
EOF
} else {
$ret .= pp_line_numbers(__LINE__, <<EOF);
{
my (\$foo, \$overload_sub);
use overload '$op' => \$overload_sub = sub(;\@) {
return $fullname($bitwise_passon) unless ref \$_[1]
&& (ref \$_[1] ne '$::PDLOBJ')
&& defined(\$foo = overload::Method(\$_[1], '$op'))
&& \$foo != \$overload_sub; # recursion guard
goto &\$foo;
Carp::confess("$fullname: overloaded '$op' given undef")
if grep !defined, \@_[0,1];
return $fullname($bitwise_passon) unless ref \$_[1]
&& (ref \$_[1] ne '$::PDLOBJ')
&& defined(\$foo = overload::Method(\$_[1], '$op'))
&& \$foo != \$overload_sub; # recursion guard
goto &\$foo;
};
}
EOF
}
$ret .= pp_line_numbers(__LINE__, <<EOF) if $mutator;
# in1, in2, out, swap if true
use overload '$op=' => sub { $fullname(\$_[0]->inplace, \$_[1]); \$_[0] };
use overload '$op=' => sub {
Carp::confess("$fullname: overloaded '$op=' given undef")
if grep !defined, \@_[0,1];
$fullname(\$_[0]->inplace, \$_[1]); \$_[0]
};
EOF
$::PDLOVERLOAD .= "$ret}\n";
my @args = @{ $sig->args_callorder };
Expand Down
5 changes: 5 additions & 0 deletions t/ops.t
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,11 @@ is $@, '', 'inplace += worked';
is $pa.'', 2, 'inplace += right value after';
}

eval { my $res = pdl(3) + undef };
like $@, qr/given undef/, 'error on overloaded op with undef arg';
eval { (my $t = pdl(3)) += undef };
like $@, qr/given undef/, 'error on overloaded op= with undef arg';

{
# log10 now uses C library
# check using scalars and ndarrays
Expand Down

0 comments on commit 6c692eb

Please sign in to comment.