D issues are now tracked on GitHub. This Bugzilla instance remains as a read-only archive.
Issue 17992 - auto return type and null for classes
Summary: auto return type and null for classes
Status: RESOLVED INVALID
Alias: None
Product: D
Classification: Unclassified
Component: dmd (show other issues)
Version: D2
Hardware: All All
: P1 normal
Assignee: No Owner
URL:
Keywords:
Depends on:
Blocks:
 
Reported: 2017-11-19 07:36 UTC by Temtaime
Modified: 2020-03-21 03:56 UTC (History)
1 user (show)

See Also:


Attachments

Note You need to log in before you can comment on or make changes to this issue.
Description Temtaime 2017-11-19 07:36:25 UTC
class C
{
	int v;

	C parent;
	C[] childs;

	auto foo(int a)
	{
		a -= v;

		if(parent && a < 0)
		{
			return null;
		}

		foreach(c; childs)
		{
			if(auto r = c.foo(a))
			{
				pragma(msg, typeof(r));
				return r;
			}
		}

		if(parent)
		{
			return this;
		}

		return null;
	}
}

void main()
{
	auto a = new C, b = new C;

	a.v = 12;

	b.parent = a;
	a.childs ~= b;

	assert(a.foo(123) is b);
}

It passes, but prints typeof(null)
It should print C or give an error with pragma or doesn't compile at all.

LDC team says it's impossible to generate code from frontend data so this example doesn't work with ldc.
Comment 1 RazvanN 2018-06-14 10:29:43 UTC
Reduced test case:

class V
{}

auto foo(int a)
{
    if (a == 1)
        return null;

    pragma(msg, typeof(return));
    return new V();
}

void main()
{}

prints: typeof(null)

I'm not sure if this bug is valid. When semantic analysis is performed at the point where typeof is evaluated the inference of the return type of foo (in both examples) has only seen return statements of null. This makes inference deduce that the type of foo is typeof(null) and this is true for that particular point.
Changing this would require moving the typeof logic from semantic1 to semantic2 or semantic3 so that when typeof is encountered, the whole foo function has been typechecked.