shiika icon indicating copy to clipboard operation
shiika copied to clipboard

From `module` to `trait`

Open yhara opened this issue 1 year ago • 0 comments

I'm considering renaming module to trait.

The biggest difference between Ruby modules and Rust traits is in the case of name confilicts.

In Rust you can implement both traits A and B for a struct:

trait A{
    fn foo(self)->i32;
}
trait B{
    fn foo(self)->bool;
}
struct X(i32);
impl A for X{
    fn foo(self)->i32{
        3
    }
}
impl B for X{
    fn foo(self)->bool{
        false
    }
}

When calling foo, you need to make it clear which foo is intended or you get this error.

  --> src/main.rs:3:3
   |
3  | x.foo();
   |   ^^^ multiple `foo` found
   |

In Ruby, you also can include modules A and B into a class:

module A       
  def foo
    3
  end
end
module B
  def foo
    false
  end
end
class X
  include A
  include B
end

However what you can call is the foo of B only because that of A is overwritten by the second call of include (yes this is a method in Ruby.) As a result p X.new.foo prints false in this case.

Ruby is so dynamic and has a lot of tools to deal with such situation. However since Shiika is a statically-typed language, I think Rust-like approach is better. And if we choose the Rust-like semantics for name collision, it may be confusing if it's still named module.

New syntax (tentative)

trait A
  requires def foo -> Int
end
trait B
  requires def foo -> Bool
end
class X
  implements A with
    def foo -> Int
      3
    end
  end
  implements B with
    def foo -> Bool
      false
    end
  end
end

yhara avatar Nov 27 '23 15:11 yhara