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