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