1 package Mouse::Meta::Method::Constructor;
5 sub generate_constructor_method_inline {
6 my ($class, $meta) = @_;
8 my @attrs = $meta->compute_all_applicable_attributes; # this one is using by evaled code
9 my $buildall = $class->_generate_BUILDALL($meta);
10 my $buildargs = $class->_generate_BUILDARGS();
11 my $processattrs = $class->_generate_processattrs($meta, \@attrs);
16 my \$args = $buildargs;
17 my \$instance = bless {}, \$class;
24 warn $code if $ENV{DEBUG};
32 sub _generate_processattrs {
33 my ($class, $meta, $attrs) = @_;
35 for my $index (0..scalar(@$attrs)-1) {
36 my $attr = $attrs->[$index];
37 my $from = $attr->init_arg;
38 my $key = $attr->name;
41 if ($attr->should_coerce) {
42 push @code, "\$args->{\$from} = \$attr->coerce_constraint( \$args->{\$from} );";
44 if ($attr->has_type_constraint) {
45 push @code, "\$attr->verify_type_constraint( \$args->{\$from} );";
47 push @code, "\$instance->{'$key'} = \$args->{\$from};";
48 if ($attr->is_weak_ref) {
49 push @code, "weaken( \$instance->{'$key'} ) if ref( \$instance->{'$key'} );";
51 if ( $attr->has_trigger ) {
52 push @code, "\$attr->trigger->( \$instance, \$args->{\$from}, \$attr );";
58 if ( $attr->has_default || $attr->has_builder ) {
59 unless ( $attr->is_lazy ) {
60 my $default = $attr->default;
61 my $builder = $attr->builder;
62 if ($attr->has_builder) {
63 push @code, "my \$value = \$instance->$builder;";
64 } elsif (ref($default) eq 'CODE') {
65 push @code, "my \$value = \$attr->default()->();";
67 push @code, "my \$value = \$attr->default();";
69 if ($attr->should_coerce) {
70 push @code, "\$value = \$attr->coerce_constraint(\$value);";
72 if ($attr->has_type_constraint) {
73 push @code, "\$attr->verify_type_constraint(\$value);";
75 push @code, "\$instance->{'$key'} = \$value;";
76 if ($attr->is_weak_ref) {
77 push @code, "weaken( \$instance->{'$key'} ) if ref( \$instance->{'$key'} );";
83 if ( $attr->is_required ) {
84 q{Carp::confess("Attribute (} . $attr->name . q{) is required");};
92 my \$attr = \$attrs[$index];
94 if (defined(\$from) && exists(\$args->{\$from})) {
103 return join "\n", @res;
106 sub _generate_BUILDARGS {
109 if ( scalar @_ == 1 ) {
110 if ( defined $_[0] ) {
111 ( ref( $_[0] ) eq 'HASH' )
112 || Carp::confess "Single parameters to new() must be a HASH ref";
126 sub _generate_BUILDALL {
127 my ($class, $meta) = @_;
128 return '' unless $meta->name->can('BUILD');
131 push @code, q{no strict 'refs';};
132 push @code, q{no warnings 'once';};
134 for my $class ($meta->linearized_isa) {
135 if (*{ $class . '::BUILD' }{CODE}) {
136 push @code, qq{${class}::BUILD->(\$instance, \$args);};
139 return join "\n", @code;