vein-lang / vein

🔮⚡️Vein is an open source high-level strictly-typed programming language with a standalone OS, arm and quantum computing support.
https://vein-lang.org
MIT License
47 stars 6 forks source link

[proposal] Extensions Types or Traits #255

Open ZverGuy opened 1 month ago

ZverGuy commented 1 month ago

Extensions Types or Traits

Summary

Add support to extending class functionality without inheritance or composition

Motivation

Add support to extending class functionality without inheritance can decrease count of boilerplate code

With this feature creating adapters and wrapper for implement interfaces are useless

Just write a extension type or 'impl' for underlying type.

The purpose of "extensions" is to augment or adapt existing types to new scenarios, when those types are not under your control, or where changing them would negatively impact other uses of them. The adaptation can be in the form of adding new function members as well as implementing additional interfaces.

Example

Detailed design

Design based on https://github.com/dotnet/csharplang/blob/main/proposals/extensions.md

Syntax

type_declaration
    | extension_declaration // add
    | ...
    ;

extension_declaration
    : extension_modifier* ('implicit' | 'explicit') 'extension' identifier type_parameter_list? ('for' type)? type_parameter_constraints_clause* extension_body
    ;

extension_body
    : '{' extension_member_declaration* '}'
    ;

extension_member_declaration
    : constant_declaration
    | field_declaration
    | method_declaration
    | property_declaration
    | event_declaration
    | indexer_declaration
    | operator_declaration
    | type_declaration
    ;

extension_modifier
    | 'partial'
    | 'unsafe'
    | 'static'
    | 'protected'
    | 'internal'
    | 'private'
    | 'file'
    ;

but unlike c# proposal, in vein lang extension types should support to implement interfaces.

code example

class U
{
    public void M2() { }
}

explicit extension R : U
{
    public void M2() { } // warning: needs `new`
    void M()
    {
        M2(); // find `R.M2()`, no ambiguity
    }
}

Alternatives

Rust Traits

0xF6 commented 2 weeks ago

Okay Create /specs/extensions.md and describe the specification After pouring in the specification, work on the prototype will begin

ZverGuy commented 2 weeks ago

Okay Create /specs/extensions.md and describe the specification After pouring in the specification, work on the prototype will begin

https://github.com/vein-lang/vein/pull/259

ZverGuy commented 2 weeks ago

Spec merged in upstream @0xF6 for now I'm waiting prototype