[next edition] Error when aliasing a method of a variable

https://dlang.org/spec/legacy#alias-instance-member

Also only error when the member actually needs `this`.
Show kind and name of member in error message.
This commit is contained in:
Nick Treleaven 2024-08-26 11:54:52 +01:00 committed by The Dlang Bot
parent 519a8a2eeb
commit 4a5c56d0f7
3 changed files with 20 additions and 6 deletions

View file

@ -5358,9 +5358,11 @@ void aliasSemantic(AliasDeclaration ds, Scope* sc)
mt.ident != Id.This && mt.ident != Id._super) mt.ident != Id.This && mt.ident != Id._super)
{ {
s = tident.toDsymbol(sc); s = tident.toDsymbol(sc);
if (s && s.isVarDeclaration()) { // don't error for `var1.static_symbol`
error(mt.loc, "cannot alias member of variable `%s`", mt.ident.toChars()); if (s && s.needThis()) {
errorSupplemental(mt.loc, "Use `typeof(%s)` instead to preserve behaviour", error(ds.loc, "cannot alias %s member `%s` of variable `%s`",
s.kind(), s.toChars(), mt.ident.toChars());
errorSupplemental(ds.loc, "Use `typeof(%s)` instead to preserve behaviour",
mt.ident.toChars()); mt.ident.toChars());
} }
} }

View file

@ -1,7 +1,7 @@
/* /*
TEST_OUTPUT: TEST_OUTPUT:
--- ---
fail_compilation/alias_instance_member.d(18): Error: cannot alias member of variable `that` fail_compilation/alias_instance_member.d(18): Error: cannot alias variable member `v` of variable `that`
fail_compilation/alias_instance_member.d(18): Use `typeof(that)` instead to preserve behaviour fail_compilation/alias_instance_member.d(18): Use `typeof(that)` instead to preserve behaviour
--- ---
*/ */
@ -17,6 +17,7 @@ struct Foo
alias a = this.v; // OK alias a = this.v; // OK
alias b = that.v; alias b = that.v;
assert(&a is &b); assert(&a is &b);
alias b2 = typeof(that).v; // OK
} }
} }

View file

@ -1,8 +1,10 @@
/* /*
TEST_OUTPUT: TEST_OUTPUT:
--- ---
fail_compilation/alias_instance_member2.d(20): Error: cannot alias member of variable `f` fail_compilation/alias_instance_member2.d(26): Error: cannot alias variable member `v` of variable `f`
fail_compilation/alias_instance_member2.d(20): Use `typeof(f)` instead to preserve behaviour fail_compilation/alias_instance_member2.d(26): Use `typeof(f)` instead to preserve behaviour
fail_compilation/alias_instance_member2.d(30): Error: cannot alias function member `fun` of variable `f`
fail_compilation/alias_instance_member2.d(30): Use `typeof(f)` instead to preserve behaviour
--- ---
*/ */
@ -12,10 +14,19 @@ module aim;
struct Foo struct Foo
{ {
int v; int v;
static int w;
enum x = 5;
void fun() {}
static void gun() {}
} }
struct Bar struct Bar
{ {
Foo f; Foo f;
alias v = f.v; alias v = f.v;
alias v2 = typeof(f).v; // OK
alias w = f.w; // OK
alias x = f.x; // OK
alias fun = f.fun;
alias gun = f.gun; // OK
} }