Skip to content

Commit

Permalink
Create attribute accessors. Mostly stolen from nqpclr
Browse files Browse the repository at this point in the history
  • Loading branch information
bacek committed Feb 18, 2011
1 parent 6f1b093 commit 549d447
Show file tree
Hide file tree
Showing 3 changed files with 61 additions and 0 deletions.
40 changes: 40 additions & 0 deletions src/metamodel/how/NQPAttribute.pm
Expand Up @@ -26,4 +26,44 @@ knowhow NQPAttribute {
method box_target() {
$!box_target ?? 1 !! 0
}

method compose($obj) {
my $long_name := ~$!name;
if self.has_mutator {
my $method := pir::substr($long_name, 1);
unless has_method($obj, $method, 0) {
$obj.HOW.add_method($obj.WHAT, $method, method ($value?) {
pir::setattribute__vppsp(self, $obj.WHAT, $long_name, $value)
if pir::defined($value);

pir::getattribute__ppps(self, $obj.WHAT, $long_name);
}
);
}
}
else {
my $method := pir::substr($long_name, 2);
unless has_method($obj, $method, 0) {
$obj.HOW.add_method($obj, $method,
method () {
pir::getattribute__PPPs(self, $obj.WHAT, $long_name);
}
);
}
}
}

# Hack to check twigil.
method has_mutator() {
pir::substr(~$!name, 1, 1) ne '!';
}

sub has_method($target, $name, $local) {
my @methods := $target.HOW.methods($target, :local($local));
for @methods {
if $_ eq $name { return 1; }
}
return 0;
}

}
3 changes: 3 additions & 0 deletions src/metamodel/how/NQPClassHOW.pm
Expand Up @@ -146,6 +146,9 @@ knowhow NQPClassHOW {
# Incorporate any new multi candidates (needs MRO built).
self.incorporate_multi_candidates($obj);

# Compose attributes.
for self.attributes($obj, :local<0> ) { $_.compose($obj) }

# Publish type and method caches.
self.publish_type_cache($obj);
self.publish_method_cache($obj);
Expand Down
18 changes: 18 additions & 0 deletions t/nqp/58-attrs.t
@@ -0,0 +1,18 @@
#! nqp

plan(2);

class Foo {
has $bar;

has $!answer;
method question() { $!answer := 42 };
};

my $foo := Foo.new;

$foo.question();
ok($foo.answer == 42, "Read-only accessors works");

$foo.bar(42);
ok($foo.bar == 42, 'Read-write accessors works');

0 comments on commit 549d447

Please sign in to comment.