Skip to content

Commit

Permalink
report an error when making an object of an incomplete class
Browse files Browse the repository at this point in the history
instead of asserting or crashing

Fixes Perl#22159
  • Loading branch information
tonycoz committed Apr 23, 2024
1 parent 17535c9 commit a564fbe
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 0 deletions.
5 changes: 5 additions & 0 deletions class.c
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,11 @@ XS(injected_constructor)
Perl_warn(aTHX_ "Odd number of arguments passed to %" HvNAMEf_QUOTEDPREFIX " constructor",
HvNAMEfARG(stash));

if (!aux->xhv_class_initfields_cv) {
Perl_croak(aTHX_ "Cannot create an object of incomplete class %" HvNAMEf_QUOTEDPREFIX,
HvNAMEfARG(stash));
}

HV *params = NULL;
{
/* Set up params HV */
Expand Down
12 changes: 12 additions & 0 deletions pod/perldiag.pod
Original file line number Diff line number Diff line change
Expand Up @@ -731,6 +731,18 @@ be directly assigned to.
an C<@ISA> array, and the array is not empty. This is not permitted, as it
would lead to a class with inconsistent inheritance.

=item Cannot create an object of incomplete class "%s"

(F) An attempt was made to create an object of a class where the start
of the class definition has been seen, but the class has not been
completed.

This can happen for a failed eval, or if you attempt to create an
object at compile time before the class is complete:

eval "class Foo {"; Foo->new; # error
class Bar { BEGIN { Bar->new } }; # error

=item Cannot find encoding "%s"

(S io) You tried to apply an encoding that did not exist to a filehandle,
Expand Down
18 changes: 18 additions & 0 deletions t/lib/croak/class
Original file line number Diff line number Diff line change
Expand Up @@ -137,3 +137,21 @@ class XXX {
}
EXPECT
Cannot use __CLASS__ outside of a method or field initializer expression at - line 5.
########
# NAME try to create an object of incomplete class (error)
use v5.36;
use feature 'class';
no warnings 'experimental::class';
eval "class C {";
C->new;
EXPECT
Cannot create an object of incomplete class "C" at - line 5.
########
# NAME try to create an object of incomplete class (compile-time)
use v5.36;
use feature 'class';
no warnings 'experimental::class';
class C { BEGIN { C->new; } };
EXPECT
Cannot create an object of incomplete class "C" at - line 4.
BEGIN failed--compilation aborted at - line 4.

0 comments on commit a564fbe

Please sign in to comment.