call BUILDARGS if defined
[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   if ($into->can('BUILDARGS') ) {
48       $body .= $self->_generate_args_via_buildargs;
49   } else {
50       $body .= $self->_generate_args;
51   }
52   $body .= $self->_check_required($spec);
53   $body .= '    my $new = '.$self->construction_string.";\n";
54   $body .= $self->_assign_new($spec);
55   if ($into->can('BUILD')) {
56     require Method::Generate::BuildAll;
57     $body .= Method::Generate::BuildAll->new->buildall_body_for(
58       $into, '$new', '$args'
59     );
60   }
61   $body .= '    return $new;'."\n";
62   quote_sub
63     "${into}::${name}" => $body,
64     $self->{captures}, $quote_opts||{}
65   ;
66 }
67
68 sub _handle_subconstructor {
69   my ($self, $into, $name) = @_;
70   if (my $gen = $self->{subconstructor_generator}) {
71     '    if ($class ne '.perlstring($into).') {'."\n".
72     '      '.$gen.";\n".
73     '      return $class->'.$name.'(@_)'.";\n".
74     '    }'."\n";
75   } else {
76     ''
77   }
78 }
79
80 sub _cap_call {
81   my ($self, $code, $captures) = @_;
82   @{$self->{captures}}{keys %$captures} = values %$captures if $captures;
83   $code;
84 }
85
86 sub _generate_args_via_buildargs {
87   my ($self) = @_;
88   q{    my $args = $class->BUILDARGS(@_);}."\n";
89 }
90
91 sub _generate_args {
92   my ($self) = @_;
93   q{    my $args = ref($_[0]) eq 'HASH' ? $_[0] : { @_ };}."\n";
94 }
95
96 sub _assign_new {
97   my ($self, $spec) = @_;
98   my (@init, @slots, %test);
99   my $ag = $self->accessor_generator;
100   NAME: foreach my $name (sort keys %$spec) {
101     my $attr_spec = $spec->{$name};
102     unless ($ag->is_simple_attribute($name, $attr_spec)) {
103       next NAME unless defined($attr_spec->{init_arg})
104                          or $ag->has_eager_default($name, $attr_spec);
105       $test{$name} = $attr_spec->{init_arg};
106       next NAME;
107     }
108     next NAME unless defined(my $i = $attr_spec->{init_arg});
109     push @init, $i;
110     push @slots, $name;
111   }
112   return '' unless @init or %test;
113   join '', (
114     @init
115       ? '    '.$self->_cap_call($ag->generate_multi_set(
116           '$new', [ @slots ], '@{$args}{qw('.join(' ',@init).')}'
117         )).";\n"
118       : ''
119   ), map {
120     my $arg_key = perlstring($test{$_});
121     my $test = "exists \$args->{$arg_key}";
122     my $source = "\$args->{$arg_key}";
123     my $attr_spec = $spec->{$_};
124     $self->_cap_call($ag->generate_populate_set(
125       '$new', $_, $attr_spec, $source, $test
126     ));
127   } sort keys %test;
128 }
129
130 sub _check_required {
131   my ($self, $spec) = @_;
132   my @required_init =
133     map $spec->{$_}{init_arg},
134       grep $spec->{$_}{required},
135         sort keys %$spec;
136   return '' unless @required_init;
137   '    if (my @missing = grep !exists $args->{$_}, qw('
138     .join(' ',@required_init).')) {'."\n"
139     .q{      die "Missing required arguments: ".join(', ', sort @missing);}."\n"
140     ."    }\n";
141 }
142
143 sub _check_isa {
144   my ($self, $spec) = @_;
145   my $acc = $self->accessor_generator;
146   my $captures = $self->{captures};
147   my $check = '';
148   foreach my $name (sort keys %$spec) {
149     my ($init, $isa) = @{$spec->{$name}}{qw(init_arg isa)};
150     next unless $init and $isa;
151     my $init_str = perlstring($init);
152     my ($code, $add_captures) = $acc->generate_isa_check(
153       $name, "\$args->{${init_str}}", $isa
154     );
155     @{$captures}{keys %$add_captures} = values %$add_captures;
156     $check .= "    ${code}".(
157       (not($spec->{lazy}) and ($spec->{default} or $spec->{builder})
158         ? ";\n"
159         : "if exists \$args->{${init_str}};\n"
160       )
161     );
162   }
163   return $check;
164 }
165
166 sub _fire_triggers {
167   my ($self, $spec) = @_;
168   my $acc = $self->accessor_generator;
169   my $captures = $self->{captures};
170   my $fire = '';
171   foreach my $name (sort keys %$spec) {
172     my ($init, $trigger) = @{$spec->{$name}}{qw(init_arg trigger)};
173     next unless $init && $trigger;
174     my ($code, $add_captures) = $acc->generate_trigger(
175       $name, '$new', $acc->generate_simple_get('$new', $name), $trigger
176     );
177     @{$captures}{keys %$add_captures} = values %$add_captures;
178     $fire .= "    ${code} if exists \$args->{${\perlstring $init}};\n";
179   }
180   return $fire;
181 }
182
183 1;