1 package Method::Generate::Accessor;
5 use base qw(Moo::Object);
8 use Scalar::Util 'blessed';
10 use Module::Runtime qw(use_module);
15 _maybe_load_module('Class::XSAccessor')
17 (eval { Class::XSAccessor->VERSION('1.07') })
23 my ($pkg, $method, $type) = @_;
24 die "You cannot overwrite a locally defined method ($method) with @{[ $type || 'an accessor' ]}";
28 my ($self, $into, $name, $spec, $quote_opts) = @_;
29 $spec->{allow_overwrite}++ if $name =~ s/^\+//;
30 die "Must have an is" unless my $is = $spec->{is};
32 $spec->{reader} = $name unless exists $spec->{reader};
33 } elsif ($is eq 'rw') {
34 $spec->{accessor} = $name unless exists $spec->{accessor}
35 or ( $spec->{reader} and $spec->{writer} );
36 } elsif ($is eq 'lazy') {
37 $spec->{reader} = $name unless exists $spec->{reader};
39 $spec->{builder} ||= '_build_'.$name unless $spec->{default};
40 } elsif ($is eq 'rwp') {
41 $spec->{reader} = $name unless exists $spec->{reader};
42 $spec->{writer} = "_set_${name}" unless exists $spec->{writer};
43 } elsif ($is ne 'bare') {
44 die "Unknown is ${is}";
46 if (exists $spec->{builder}) {
47 if(ref $spec->{builder}) {
48 die "Invalid builder for $into->$name - not a method name, coderef or"
49 . " code-convertible object"
50 unless ref $spec->{builder} eq 'CODE'
51 or (blessed($spec->{builder}) and eval { \&{$spec->{builder}} });
52 $spec->{builder_sub} = $spec->{builder};
55 $spec->{builder} = '_build_'.$name if ($spec->{builder}||0) eq 1;
56 die "Invalid builder for $into->$name - not a valid method name"
57 if $spec->{builder} !~ /\A[A-Za-z_][A-Za-z0-9_]*(?:::[A-Za-z_][A-Za-z0-9_]*)*\z/;
59 if (($spec->{predicate}||0) eq 1) {
60 $spec->{predicate} = $name =~ /^_/ ? "_has${name}" : "has_${name}";
62 if (($spec->{clearer}||0) eq 1) {
63 $spec->{clearer} = $name =~ /^_/ ? "_clear${name}" : "clear_${name}";
65 if (($spec->{trigger}||0) eq 1) {
66 $spec->{trigger} = quote_sub('shift->_trigger_'.$name.'(@_)');
69 for my $setting (qw( isa coerce )) {
70 next if !exists $spec->{$setting};
71 $self->_validate_codulatable($setting, $spec->{$setting}, "$into->$name");
74 if (exists $spec->{default}) {
75 if (!defined $spec->{default} || ref $spec->{default}) {
76 $self->_validate_codulatable('default', $spec->{default}, "$into->$name", 'or a non-ref');
80 if (exists $spec->{moosify}) {
81 if (ref $spec->{moosify} ne 'ARRAY') {
82 $spec->{moosify} = [$spec->{moosify}];
85 for my $spec (@{$spec->{moosify}}) {
86 $self->_validate_codulatable('moosify', $spec, "$into->$name");
91 if (my $reader = $spec->{reader}) {
92 _die_overwrite($into, $reader, 'a reader')
93 if !$spec->{allow_overwrite} && *{_getglob("${into}::${reader}")}{CODE};
94 if (our $CAN_HAZ_XS && $self->is_simple_get($name, $spec)) {
95 $methods{$reader} = $self->_generate_xs(
96 getters => $into, $reader, $name, $spec
99 $self->{captures} = {};
101 quote_sub "${into}::${reader}"
102 => ' die "'.$reader.' is a read-only accessor" if @_ > 1;'."\n"
103 .$self->_generate_get($name, $spec)
104 => delete $self->{captures}
108 if (my $accessor = $spec->{accessor}) {
109 _die_overwrite($into, $accessor, 'an accessor')
110 if !$spec->{allow_overwrite} && *{_getglob("${into}::${accessor}")}{CODE};
113 && $self->is_simple_get($name, $spec)
114 && $self->is_simple_set($name, $spec)
116 $methods{$accessor} = $self->_generate_xs(
117 accessors => $into, $accessor, $name, $spec
120 $self->{captures} = {};
121 $methods{$accessor} =
122 quote_sub "${into}::${accessor}"
123 => $self->_generate_getset($name, $spec)
124 => delete $self->{captures}
128 if (my $writer = $spec->{writer}) {
129 _die_overwrite($into, $writer, 'a writer')
130 if !$spec->{allow_overwrite} && *{_getglob("${into}::${writer}")}{CODE};
133 && $self->is_simple_set($name, $spec)
135 $methods{$writer} = $self->_generate_xs(
136 setters => $into, $writer, $name, $spec
139 $self->{captures} = {};
141 quote_sub "${into}::${writer}"
142 => $self->_generate_set($name, $spec)
143 => delete $self->{captures}
147 if (my $pred = $spec->{predicate}) {
148 _die_overwrite($into, $pred, 'a predicate')
149 if !$spec->{allow_overwrite} && *{_getglob("${into}::${pred}")}{CODE};
151 quote_sub "${into}::${pred}" =>
152 ' '.$self->_generate_simple_has('$_[0]', $name, $spec)."\n"
155 if (my $pred = $spec->{builder_sub}) {
156 _install_coderef( "${into}::$spec->{builder}" => $spec->{builder_sub} );
158 if (my $cl = $spec->{clearer}) {
159 _die_overwrite($into, $cl, 'a clearer')
160 if !$spec->{allow_overwrite} && *{_getglob("${into}::${cl}")}{CODE};
162 quote_sub "${into}::${cl}" =>
163 $self->_generate_simple_clear('$_[0]', $name, $spec)."\n"
166 if (my $hspec = $spec->{handles}) {
167 my $asserter = $spec->{asserter} ||= '_assert_'.$name;
169 if (ref($hspec) eq 'ARRAY') {
170 map [ $_ => $_ ], @$hspec;
171 } elsif (ref($hspec) eq 'HASH') {
172 map [ $_ => ref($hspec->{$_}) ? @{$hspec->{$_}} : $hspec->{$_} ],
174 } elsif (!ref($hspec)) {
175 map [ $_ => $_ ], use_module('Role::Tiny')->methods_provided_by(use_module($hspec))
177 die "You gave me a handles of ${hspec} and I have no idea why";
180 foreach my $delegation_spec (@specs) {
181 my ($proxy, $target, @args) = @$delegation_spec;
182 _die_overwrite($into, $proxy, 'a delegation')
183 if !$spec->{allow_overwrite} && *{_getglob("${into}::${proxy}")}{CODE};
184 $self->{captures} = {};
186 quote_sub "${into}::${proxy}" =>
187 $self->_generate_delegation($asserter, $target, \@args),
188 delete $self->{captures}
192 if (my $asserter = $spec->{asserter}) {
193 $self->{captures} = {};
196 $methods{$asserter} =
197 quote_sub "${into}::${asserter}" => $self->_generate_asserter($name, $spec),
198 delete $self->{captures}
204 sub is_simple_attribute {
205 my ($self, $name, $spec) = @_;
206 # clearer doesn't have to be listed because it doesn't
207 # affect whether defined/exists makes a difference
209 qw(lazy default builder coerce isa trigger predicate weak_ref);
213 my ($self, $name, $spec) = @_;
214 !($spec->{lazy} and ($spec->{default} or $spec->{builder}));
218 my ($self, $name, $spec) = @_;
219 !grep $spec->{$_}, qw(coerce isa trigger weak_ref);
222 sub has_eager_default {
223 my ($self, $name, $spec) = @_;
224 (!$spec->{lazy} and (exists $spec->{default} or $spec->{builder}));
228 my ($self, $name, $spec) = @_;
229 my $simple = $self->_generate_simple_get('$_[0]', $name, $spec);
230 if ($self->is_simple_get($name, $spec)) {
233 $self->_generate_use_default(
234 '$_[0]', $name, $spec,
235 $self->_generate_simple_has('$_[0]', $name, $spec),
240 sub _generate_simple_has {
241 my ($self, $me, $name) = @_;
242 "exists ${me}->{${\perlstring $name}}";
245 sub _generate_simple_clear {
246 my ($self, $me, $name) = @_;
247 " delete ${me}->{${\perlstring $name}}\n"
250 sub generate_get_default {
252 $self->{captures} = {};
253 my $code = $self->_generate_get_default(@_);
254 ($code, delete $self->{captures});
257 sub _generate_use_default {
258 my ($self, $me, $name, $spec, $test) = @_;
259 my $get_value = $self->_generate_get_default($me, $name, $spec);
260 if ($spec->{coerce}) {
261 $get_value = $self->_generate_coerce(
267 .$self->_generate_simple_get($me, $name, $spec)."\n:"
269 ? " do {\n my \$value = ".$get_value.";\n"
270 ." ".$self->_generate_isa_check($name, '$value', $spec->{isa}).";\n"
271 ." ".$self->_generate_simple_set($me, $name, $spec, '$value')."\n"
273 : ' ('.$self->_generate_simple_set($me, $name, $spec, $get_value).")\n");
276 sub _generate_get_default {
277 my ($self, $me, $name, $spec) = @_;
278 if (exists $spec->{default}) {
280 ? $self->_generate_call_code($name, 'default', $me, $spec->{default})
281 : perlstring $spec->{default};
284 "${me}->${\$spec->{builder}}"
288 sub generate_simple_get {
289 my ($self, @args) = @_;
290 $self->_generate_simple_get(@args);
293 sub _generate_simple_get {
294 my ($self, $me, $name) = @_;
295 my $name_str = perlstring $name;
296 "${me}->{${name_str}}";
300 my ($self, $name, $spec) = @_;
301 if ($self->is_simple_set($name, $spec)) {
302 $self->_generate_simple_set('$_[0]', $name, $spec, '$_[1]');
304 my ($coerce, $trigger, $isa_check) = @{$spec}{qw(coerce trigger isa)};
305 my $value_store = '$_[0]';
308 $value_store = '$value';
309 $code = "do { my (\$self, \$value) = \@_;\n"
311 .$self->_generate_coerce($name, $value_store, $coerce).";\n";
314 $code = "do { my \$self = shift;\n";
318 " ".$self->_generate_isa_check($name, $value_store, $isa_check).";\n";
320 my $simple = $self->_generate_simple_set('$self', $name, $spec, $value_store);
322 my $fire = $self->_generate_trigger($name, '$self', $value_store, $trigger);
324 " ".$simple.";\n ".$fire.";\n"
327 $code .= " ".$simple.";\n";
334 sub generate_coerce {
336 $self->{captures} = {};
337 my $code = $self->_generate_coerce(@_);
338 ($code, delete $self->{captures});
342 my ($name, $init_arg) = @_;
343 return perlstring($name) if !defined($init_arg) or $init_arg eq $name;
344 return perlstring($name).' (constructor argument: '.perlstring($init_arg).')';
347 sub _generate_coerce {
348 my ($self, $name, $value, $coerce, $init_arg) = @_;
349 $self->_generate_die_prefix(
353 $self->_generate_call_code($name, 'coerce', "${value}", $coerce)
357 sub generate_trigger {
359 $self->{captures} = {};
360 my $code = $self->_generate_trigger(@_);
361 ($code, delete $self->{captures});
364 sub _generate_trigger {
365 my ($self, $name, $obj, $value, $trigger) = @_;
366 $self->_generate_call_code($name, 'trigger', "${obj}, ${value}", $trigger);
369 sub generate_isa_check {
370 my ($self, @args) = @_;
371 $self->{captures} = {};
372 my $code = $self->_generate_isa_check(@args);
373 ($code, delete $self->{captures});
376 sub _generate_die_prefix {
377 my ($self, $name, $prefix, $init_arg, $inside) = @_;
379 $self->{captures}{'$__DIE__'} ||= \ sub {
380 our ($CurrentArgument, $CurrentAttribute, $CurrentStep, $OrigSigDie);
381 $OrigSigDie ||= sub { die $_[0] };
383 my $attr_desc = _attr_desc($CurrentAttribute, $CurrentArgument);
384 $OrigSigDie->("$CurrentStep for $attr_desc failed: $_[0]");
388 .' local $Method::Generate::Accessor::CurrentArgument = '
389 . (defined $init_arg ? B::perlstring($init_arg) : 'undef') . ";\n"
390 .' local $Method::Generate::Accessor::CurrentAttribute = '
391 . B::perlstring($name) . ";\n"
392 .' local $Method::Generate::Accessor::CurrentStep = '
393 . B::perlstring($prefix) . ";\n"
394 .' local $Method::Generate::Accessor::OrigSigDie = $SIG{__DIE__};'."\n"
395 .' local $SIG{__DIE__} = $__DIE__;'."\n"
400 sub _generate_isa_check {
401 my ($self, $name, $value, $check, $init_arg) = @_;
402 $self->_generate_die_prefix(
406 $self->_generate_call_code($name, 'isa_check', $value, $check)
410 sub _generate_call_code {
411 my ($self, $name, $type, $values, $sub) = @_;
412 $sub = \&{$sub} if blessed($sub); # coderef if blessed
413 if (my $quoted = quoted_from_sub($sub)) {
415 if ($values eq '@_' || $values eq '$_[0]') {
419 my $code = $quoted->[1];
420 if (my $captures = $quoted->[2]) {
421 my $cap_name = qq{\$${type}_captures_for_${name}};
422 $self->{captures}->{$cap_name} = \$captures;
423 Sub::Quote::inlinify(
424 $code, $values, Sub::Quote::capture_unroll($cap_name, $captures, 6), $local
427 Sub::Quote::inlinify($code, $values, undef, $local);
430 my $cap_name = qq{\$${type}_for_${name}};
431 $self->{captures}->{$cap_name} = \$sub;
432 "${cap_name}->(${values})";
436 sub generate_populate_set {
438 $self->{captures} = {};
439 my $code = $self->_generate_populate_set(@_);
440 ($code, delete $self->{captures});
443 sub _generate_populate_set {
444 my ($self, $me, $name, $spec, $source, $test, $init_arg) = @_;
445 if ($self->has_eager_default($name, $spec)) {
446 my $get_indent = ' ' x ($spec->{isa} ? 6 : 4);
447 my $get_default = $self->_generate_get_default(
451 defined($spec->{init_arg})
452 ? "(\n${get_indent} ${test}\n${get_indent} ? ${source}\n${get_indent} : "
456 if ($spec->{coerce}) {
457 $get_value = $self->_generate_coerce(
459 $spec->{coerce}, $init_arg
463 ? " {\n my \$value = ".$get_value.";\n "
464 .$self->_generate_isa_check(
465 $name, '$value', $spec->{isa}, $init_arg
467 .' '.$self->_generate_simple_set($me, $name, $spec, '$value').";\n"
469 : ' '.$self->_generate_simple_set($me, $name, $spec, $get_value).";\n"
473 .$self->_generate_trigger(
474 $name, $me, $self->_generate_simple_get($me, $name, $spec),
483 .$self->_generate_coerce(
485 $spec->{coerce}, $init_arg
491 .$self->_generate_isa_check(
492 $name, $source, $spec->{isa}, $init_arg
496 ." ".$self->_generate_simple_set($me, $name, $spec, $source).";\n"
499 .$self->_generate_trigger(
500 $name, $me, $self->_generate_simple_get($me, $name, $spec),
509 sub _generate_core_set {
510 my ($self, $me, $name, $spec, $value) = @_;
511 my $name_str = perlstring $name;
512 "${me}->{${name_str}} = ${value}";
515 sub _generate_simple_set {
516 my ($self, $me, $name, $spec, $value) = @_;
517 my $name_str = perlstring $name;
518 my $simple = $self->_generate_core_set($me, $name, $spec, $value);
520 if ($spec->{weak_ref}) {
521 require Scalar::Util;
522 my $get = $self->_generate_simple_get($me, $name, $spec);
524 # Perl < 5.8.3 can't weaken refs to readonly vars
525 # (e.g. string constants). This *can* be solved by:
527 #Internals::SetReadWrite($foo);
528 #Scalar::Util::weaken ($foo);
529 #Internals::SetReadOnly($foo);
531 # but requires XS and is just too damn crazy
532 # so simply throw a better exception
533 my $weak_simple = "do { Scalar::Util::weaken(${simple}); no warnings 'void'; $get }";
534 Moo::_Utils::lt_5_8_3() ? <<"EOC" : $weak_simple;
535 eval { Scalar::Util::weaken($simple); 1 }
536 ? do { no warnings 'void'; $get }
538 if( \$@ =~ /Modification of a read-only value attempted/) {
540 Carp::croak( sprintf (
541 'Reference to readonly value in "%s" can not be weakened on Perl < 5.8.3',
554 sub _generate_getset {
555 my ($self, $name, $spec) = @_;
556 q{(@_ > 1}."\n ? ".$self->_generate_set($name, $spec)
557 ."\n : ".$self->_generate_get($name, $spec)."\n )";
560 sub _generate_asserter {
561 my ($self, $name, $spec) = @_;
564 ." my \$val = ".$self->_generate_get($name, $spec).";\n"
565 ." unless (".$self->_generate_simple_has('$_[0]', $name, $spec).") {\n"
566 .qq! die "Attempted to access '${name}' but it is not set";\n!
571 sub _generate_delegation {
572 my ($self, $asserter, $target, $args) = @_;
573 my $arg_string = do {
575 # I could, I reckon, linearise out non-refs here using perlstring
576 # plus something to check for numbers but I'm unsure if it's worth it
577 $self->{captures}{'@curries'} = $args;
583 "shift->${asserter}->${target}(${arg_string});";
587 my ($self, $type, $into, $name, $slot) = @_;
588 Class::XSAccessor->import(
590 $type => { $name => $slot },
596 sub default_construction_string { '{}' }
598 sub _validate_codulatable {
599 my ($self, $setting, $value, $into, $appended) = @_;
600 my $invalid = "Invalid $setting '" . overload::StrVal($value)
601 . "' for $into not a coderef";
602 $invalid .= " $appended" if $appended;
604 unless (ref $value and (ref $value eq 'CODE' or blessed($value))) {
605 die "$invalid or code-convertible object";
608 unless (eval { \&$value }) {
609 die "$invalid and could not be converted to a coderef: $@";