1 package Mouse::Meta::Method::Constructor;
5 sub generate_constructor_method_inline {
6 my ($class, $meta) = @_;
7 my $buildall = $class->_generate_BUILDALL($meta);
8 my $buildargs = $class->_generate_BUILDARGS();
9 my $classname = $meta->name;
10 my $processattrs = $class->_generate_processattrs($meta);
15 my \$args = $buildargs;
16 my \$instance = bless {}, '$classname';
22 warn $code if $ENV{DEBUG};
29 sub _generate_processattrs {
30 my ($class, $meta, ) = @_;
31 my @attrs = $meta->compute_all_applicable_attributes;
33 for my $attr (@attrs) {
34 my $from = $attr->init_arg;
35 my $key = $attr->name;
38 if ($attr->should_coerce) {
39 push @code, "\$args->{\$from} = \$attr->coerce_constraint( \$args->{\$from} );";
41 if ($attr->has_type_constraint) {
42 push @code, "\$attr->verify_type_constraint( \$args->{\$from} );";
44 push @code, "\$instance->{\$key} = \$args->{\$from};";
45 push @code, "weaken( \$instance->{\$key} ) if ref( \$instance->{\$key} ) && \$attr->is_weak_ref;";
46 if ( $attr->has_trigger ) {
47 push @code, "\$attr->trigger->( \$instance, \$args->{\$from}, \$attr );";
53 if ( $attr->has_default || $attr->has_builder ) {
54 unless ( $attr->is_lazy ) {
55 my $default = $attr->default;
56 my $builder = $attr->builder;
57 if ($attr->has_builder) {
58 push @code, "my \$value = \$instance->$builder;";
59 } elsif (ref($default) eq 'CODE') {
60 push @code, "my \$value = \$attr->default()->();";
62 push @code, "my \$value = \$attr->default();";
64 if ($attr->should_coerce) {
65 push @code, "\$value = \$attr->coerce_constraint(\$value);";
67 if ($attr->has_type_constraint) {
68 push @code, "\$attr->verify_type_constraint(\$value);";
70 push @code, "\$instance->{\$key} = \$value;";
71 if ($attr->is_weak_ref) {
72 push @code, "weaken( \$instance->{\$key} ) if ref( \$instance->{\$key} );";
78 if ( $attr->is_required ) {
79 q{Carp::confess("Attribute (} . $attr->name . q{) is required");};
87 my \$attr = \$instance->meta->get_attribute_map->{'$key'};
90 if (defined(\$from) && exists(\$args->{\$from})) {
99 return join "\n", @res;
102 sub _generate_BUILDARGS {
105 if ( scalar @_ == 1 ) {
106 if ( defined $_[0] ) {
107 ( ref( $_[0] ) eq 'HASH' )
108 || Carp::confess "Single parameters to new() must be a HASH ref";
122 sub _generate_BUILDALL {
123 my ($class, $meta) = @_;
124 return '' unless $meta->name->can('BUILD');
127 push @code, q{no strict 'refs';};
128 push @code, q{no warnings 'once';};
130 for my $class ($meta->linearized_isa) {
131 if (*{ $class . '::BUILD' }{CODE}) {
132 push @code, qq{${class}::BUILD->(\$instance, \$args);};
135 return join "\n", @code;