Draco-lang / Language-suggestions

Collecting ideas for a new .NET language that could replace C#
75 stars 5 forks source link

Aliasing with generics and visibility #118

Open LPeter1997 opened 1 year ago

LPeter1997 commented 1 year ago

C# allows for type aliasing using the syntax

using Foo = Bar;

Soon with C# 12, this will be extended to mean essentially arbitrary aliasing for even things like tuples. It has a few limitations still, that I'd like to propose we resolve:

Basic feature

We could allow aliasing ourselves using a similar syntax, but maybe a better keyword:

type Foo = int32;

An alternative keyword I thought of was alias.

We could also allow aliasing in any scope, just like we allow our other features, meaning it does not have to be a top-level element, like in C#.

Generic aliasing

C# does not allow for generic aliasing, meaning the following is not legal:

using MyList<T> = System.Collection.Generic.List<T>;

We could allow this, but there is one caveat: This syntax would also need to introduce a generic constraint list, once we introduce them in the language. Example:

type MyList<T> = System.Collection.Generic.List<T>;

Aliasing with visibility

This might be a controversial one. C# does not allow type aliases to be visible outside of the file-local scope. This is somewhat understandable, but becomes annoying in places where we deal with lots of structural types and need to alias big types in every file. We could allow the alias to have a visibility, just like other language elements, meaning private by default, explicit internal or public.

Examples:

// Private to file
type Foo = int32;

// Private to project
internal type Bar = OneOf<int32, string>;

// Accessible from outside
public type Message = OneOf<int32, string, List<(int Sequence, string Tag, Contracts.MessageBody)>>;

Considerations

This feature would obviously be bounded by the language in a sense, that a C# project referencing a Draco project won't be able to see this alias, unless some aliasing mechanism can be injected in metadata that would allow for this.

Binto86 commented 1 year ago

Could we also allow something like this?

type MyList = System.Collection.Generic.List<int32>;
LPeter1997 commented 1 year ago

Yes, just like in C#, fully resolved types would be allowed

eatdrinksleepcode commented 1 year ago

No referencing the alias from outside the file

C# does not allow type aliases to be visible outside of the file-local scope.

Note that this is no longer true: with global using directives it is now possible to create an alias with project scope.

It's still not visible outside the project/assembly, of course.

LPeter1997 commented 1 year ago

Oh, this is good to know! I swear I've tried to global alias something and it didn't work. Maybe I was on an old compiler or lang revision.

Essentially global using would be an internal alias Draco then.