Skip to content

Commit

Permalink
Merge pull request #8203 from RazvanN7/Issue_5153
Browse files Browse the repository at this point in the history
Fix Issue 5153 - Struct pointer to struct variable assign error message
merged-on-behalf-of: Mike Franklin <JinShil@users.noreply.github.com>
  • Loading branch information
dlang-bot committed May 18, 2018
2 parents 7222122 + 14dfe15 commit b61d1c8
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 0 deletions.
25 changes: 25 additions & 0 deletions src/dmd/expressionsem.d
Expand Up @@ -6774,6 +6774,31 @@ private extern (C++) final class ExpressionSemanticVisitor : Visitor
* Rewrite as:
* e1 = init, e1.ctor(e2)
*/

/* Fix Issue 5153 : https://issues.dlang.org/show_bug.cgi?id=5153
* Using `new` to initialize a struct object is a common mistake, but
* the error message from the compiler is not very helpful in that
* case. If exp.e2 is a NewExp and the type of new is the same as
* the type as exp.e1 (struct in this case), then we know for sure
* that the user wants to instantiate a struct. This is done to avoid
* issuing an error when the user actually wants to call a constructor
* which receives a class object.
*
* Foo f = new Foo2(0); is a valid expression if Foo has a constructor
* which receives an instance of a Foo2 class
*/
if (exp.e2.op == TOK.new_)
{
auto newExp = cast(NewExp)(exp.e2);
if (newExp.newtype && newExp.newtype == t1)
{
error(exp.loc, "cannot implicitly convert expression `%s` of type `%s` to `%s`",
newExp.toChars(), newExp.type.toChars(), t1.toChars());
errorSupplemental(exp.loc, "Perhaps remove the `new` keyword?");
return setError();
}
}

Expression einit;
einit = new BlitExp(exp.loc, e1x, e1x.type.defaultInit(exp.loc));
einit.type = e1x.type;
Expand Down
28 changes: 28 additions & 0 deletions test/fail_compilation/fail5153.d
@@ -0,0 +1,28 @@
// https://issues.dlang.org/show_bug.cgi?id=5153

/*
TEST_OUTPUT:
---
fail_compilation/fail5153.d(26): Error: cannot implicitly convert expression `new Foo(0)` of type `Foo*` to `Foo`
fail_compilation/fail5153.d(26): Perhaps remove the `new` keyword?
---
*/

class Foo2
{
this(int) {}
}

struct Foo {
int x;
this(int x_)
{
this.x = x_;
}

this(Foo2) {}
}
void main() {
Foo f = new Foo(0);
Foo f2 = new Foo2(0);
}

0 comments on commit b61d1c8

Please sign in to comment.