Skip to content

Commit

Permalink
- Allow prefix method-calls in class has variables.
Browse files Browse the repository at this point in the history
This fixes code like:

    class Example (value) {
        has t = sqrt(value)
    }

    var obj = Example(42)
    say obj.t

Previously, the above code incorrectly died with a run-time error.
  • Loading branch information
trizen committed Mar 5, 2020
1 parent 9b74dc9 commit 98fdc39
Show file tree
Hide file tree
Showing 3 changed files with 71 additions and 1 deletion.
1 change: 1 addition & 0 deletions MANIFEST
Original file line number Diff line number Diff line change
Expand Up @@ -685,6 +685,7 @@ scripts/Tests/class_attr_inheritance.sf
scripts/Tests/class_attributes.sf
scripts/Tests/class_field_inheritance.sf
scripts/Tests/class_global_variables.sf
scripts/Tests/class_has_variables_with_prefix_methods.sf
scripts/Tests/class_inheritance.sf
scripts/Tests/class_inside_module.sf
scripts/Tests/class_redefinition.sf
Expand Down
2 changes: 1 addition & 1 deletion lib/Sidef/Parser.pm
Original file line number Diff line number Diff line change
Expand Up @@ -1194,7 +1194,7 @@ package Sidef::Parser {
# "has" class attributes
if (exists($self->{current_class}) and /\Ghas\b\h*/gc) {

local $self->{allow_class_variable} = 1;
local $self->{allow_class_variable} = 0;

my $vars = $self->parse_init_vars(
code => $opt{code},
Expand Down
69 changes: 69 additions & 0 deletions scripts/Tests/class_has_variables_with_prefix_methods.sf
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
#!/usr/bin/ruby

class Friend(name) {
method hi {
"Hello, #{name}!"
}
}

class Example(a) {
has t = sqrt(a)

has v = try { Friend("Agent #{a}") } catch { 'undefined' }
has u = try { NotDefined("foo #{a}") } catch { 'undefined' }

has w = Friend("Actor #{a + 1}")

method foo {
self.bar
}

method bar {
log(t)
}

method baz(tmp = sqrt(2)) {
tmp + 1
}

method qux(z = t) {
z + 1
}

method zoo(r = self.t) {
r - 1
}

method zzz(f = self.bar) {
f + 1
}

method friend {
v.name
}
}

var obj = Example(99)

assert_eq(obj.t, 99.sqrt)
assert_eq(obj.bar, 99.sqrt.log)
assert_eq(obj.baz, 2.sqrt + 1)
assert_eq(obj.qux, 99.sqrt + 1)
assert_eq(obj.zoo, 99.sqrt - 1)
assert_eq(obj.zzz, 99.sqrt.log + 1)

assert_eq(obj.friend, "Agent 99")
assert_eq(obj.v.hi, "Hello, Agent 99!")
assert_eq(obj.w.hi, "Hello, Actor 100!")

obj.t = 1234

assert_eq(obj.v.hi, "Hello, Agent 99!")
assert_eq(Example(7).v.hi, "Hello, Agent 7!")

assert_eq(obj.v.hi, "Hello, Agent 99!")
assert_eq(obj.w.hi, "Hello, Actor 100!")

assert_eq(obj.u, 'undefined')

say "** Test passed!"

0 comments on commit 98fdc39

Please sign in to comment.