e0746d7a41613d79d20e2313b4c7ce4b20812465
[gitmo/Moo.git] / lib / Method / Generate / Constructor.pm
1 package Method::Generate::Constructor;
2
3 use strictures 1;
4 use Sub::Quote;
5 use base qw(Moo::Object);
6 use Sub::Defer;
7 use B 'perlstring';
8
9 sub register_attribute_specs {
10   my ($self, @new_specs) = @_;
11   my $specs = $self->{attribute_specs}||={};
12   while (my ($name, $new_spec) = splice @new_specs, 0, 2) {
13     if ($name =~ s/^\+//) {
14       die "has '+${name}' given but no ${name} attribute already exists"
15         unless my $old_spec = $specs->{$name};
16       foreach my $key (keys %$old_spec) {
17         $new_spec->{$key} = $old_spec->{$key}
18           unless exists $new_spec->{$key};
19         }
20       }
21     $new_spec->{index} = scalar keys %$specs
22       unless defined $new_spec->{index};
23     $specs->{$name} = $new_spec;
24   }
25   $self;
26 }
27
28 sub all_attribute_specs {
29   $_[0]->{attribute_specs}
30 }
31
32 sub accessor_generator {
33   $_[0]->{accessor_generator}
34 }
35
36 sub construction_string {
37   my ($self) = @_;
38   $self->{construction_string}
39     or 'bless('
40        .$self->accessor_generator->default_construction_string
41        .', $class);'
42 }
43
44 sub install_delayed {
45   my ($self) = @_;
46   my $package = $self->{package};
47   defer_sub "${package}::new" => sub {
48     unquote_sub $self->generate_method(
49       $package, 'new', $self->{attribute_specs}, { no_install => 1 }
50     )
51   };
52   $self;
53 }
54
55 sub generate_method {
56   my ($self, $into, $name, $spec, $quote_opts) = @_;
57   foreach my $no_init (grep !exists($spec->{$_}{init_arg}), keys %$spec) {
58     $spec->{$no_init}{init_arg} = $no_init;
59   }
60   local $self->{captures} = {};
61   my $body = '    my $class = shift;'."\n"
62             .'    $class = ref($class) if ref($class);'."\n";
63   $body .= $self->_handle_subconstructor($into, $name);
64   my $into_buildargs = $into->can('BUILDARGS');
65   if ( $into_buildargs && $into_buildargs != \&Moo::Object::BUILDARGS ) {
66       $body .= $self->_generate_args_via_buildargs;
67   } else {
68       $body .= $self->_generate_args;
69   }
70   $body .= $self->_check_required($spec);
71   $body .= '    my $new = '.$self->construction_string.";\n";
72   $body .= $self->_assign_new($spec);
73   if ($into->can('BUILD')) {
74     require Method::Generate::BuildAll;
75     $body .= Method::Generate::BuildAll->new->buildall_body_for(
76       $into, '$new', '$args'
77     );
78   }
79   $body .= '    return $new;'."\n";
80   if ($into->can('DEMOLISH')) {
81     require Method::Generate::DemolishAll;
82     Method::Generate::DemolishAll->new->generate_method($into);
83   }
84   quote_sub
85     "${into}::${name}" => $body,
86     $self->{captures}, $quote_opts||{}
87   ;
88 }
89
90 sub _handle_subconstructor {
91   my ($self, $into, $name) = @_;
92   if (my $gen = $self->{subconstructor_handler}) {
93     '    if ($class ne '.perlstring($into).') {'."\n".
94     $gen.
95     '    }'."\n";
96   } else {
97     ''
98   }
99 }
100
101 sub _cap_call {
102   my ($self, $code, $captures) = @_;
103   @{$self->{captures}}{keys %$captures} = values %$captures if $captures;
104   $code;
105 }
106
107 sub _generate_args_via_buildargs {
108   my ($self) = @_;
109   q{    my $args = $class->BUILDARGS(@_);}."\n"
110   .q{    die "BUILDARGS did not return a hashref" unless ref($args) eq 'HASH';}
111   ."\n";
112 }
113
114 # inlined from Moo::Object - update that first.
115 sub _generate_args {
116   my ($self) = @_;
117   return <<'_EOA';
118     my $args;
119     if ( scalar @_ == 1 ) {
120         unless ( defined $_[0] && ref $_[0] eq 'HASH' ) {
121             die "Single parameters to new() must be a HASH ref"
122                 ." data => ". $_[0] ."\n";
123         }
124         $args = { %{ $_[0] } };
125     }
126     elsif ( @_ % 2 ) {
127         die "The new() method for $class expects a hash reference or a key/value list."
128                 . " You passed an odd number of arguments\n";
129     }
130     else {
131         $args = {@_};
132     }
133 _EOA
134
135 }
136
137 sub _assign_new {
138   my ($self, $spec) = @_;
139   my (@init, @slots, %test);
140   my $ag = $self->accessor_generator;
141   NAME: foreach my $name (sort keys %$spec) {
142     my $attr_spec = $spec->{$name};
143     unless ($ag->is_simple_attribute($name, $attr_spec)) {
144       next NAME unless defined($attr_spec->{init_arg})
145                          or $ag->has_eager_default($name, $attr_spec);
146       $test{$name} = $attr_spec->{init_arg};
147       next NAME;
148     }
149     next NAME unless defined(my $i = $attr_spec->{init_arg});
150     push @init, $i;
151     push @slots, $name;
152   }
153   return '' unless @init or %test;
154   join '', (
155     @init
156       ? '    '.$self->_cap_call($ag->generate_multi_set(
157           '$new', [ @slots ], '@{$args}{qw('.join(' ',@init).')}', $spec
158         )).";\n"
159       : ''
160   ), map {
161     my $arg_key = perlstring($test{$_});
162     my $test = "exists \$args->{$arg_key}";
163     my $source = "\$args->{$arg_key}";
164     my $attr_spec = $spec->{$_};
165     $self->_cap_call($ag->generate_populate_set(
166       '$new', $_, $attr_spec, $source, $test
167     ));
168   } sort keys %test;
169 }
170
171 sub _check_required {
172   my ($self, $spec) = @_;
173   my @required_init =
174     map $spec->{$_}{init_arg},
175       grep $spec->{$_}{required},
176         sort keys %$spec;
177   return '' unless @required_init;
178   '    if (my @missing = grep !exists $args->{$_}, qw('
179     .join(' ',@required_init).')) {'."\n"
180     .q{      die "Missing required arguments: ".join(', ', sort @missing);}."\n"
181     ."    }\n";
182 }
183
184 sub _check_isa {
185   my ($self, $spec) = @_;
186   my $acc = $self->accessor_generator;
187   my $captures = $self->{captures};
188   my $check = '';
189   foreach my $name (sort keys %$spec) {
190     my ($init, $isa) = @{$spec->{$name}}{qw(init_arg isa)};
191     next unless $init and $isa;
192     my $init_str = perlstring($init);
193     my ($code, $add_captures) = $acc->generate_isa_check(
194       $name, "\$args->{${init_str}}", $isa
195     );
196     @{$captures}{keys %$add_captures} = values %$add_captures;
197     $check .= "    ${code}".(
198       (not($spec->{lazy}) and ($spec->{default} or $spec->{builder})
199         ? ";\n"
200         : "if exists \$args->{${init_str}};\n"
201       )
202     );
203   }
204   return $check;
205 }
206
207 sub _fire_triggers {
208   my ($self, $spec) = @_;
209   my $acc = $self->accessor_generator;
210   my $captures = $self->{captures};
211   my $fire = '';
212   foreach my $name (sort keys %$spec) {
213     my ($init, $trigger) = @{$spec->{$name}}{qw(init_arg trigger)};
214     next unless $init && $trigger;
215     my ($code, $add_captures) = $acc->generate_trigger(
216       $name, '$new', $acc->generate_simple_get('$new', $name, $spec), $trigger
217     );
218     @{$captures}{keys %$add_captures} = values %$add_captures;
219     $fire .= "    ${code} if exists \$args->{${\perlstring $init}};\n";
220   }
221   return $fire;
222 }
223
224 1;