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