slang icon indicating copy to clipboard operation
slang copied to clipboard

__init shouldn't be able to return a value

Open jkwak-work opened this issue 11 months ago • 1 comments

It appears that slangc currently allows "__init()" functions to return a value. We should have a compiler error for this case.

Currently we have two bugs in core.meta.slang,

__generic<T:__BuiltinFloatingPointType, let N : int>
extension vector<T,N> : IFloat
{
    [OverloadRank(-1)]
    [__unsafeForceInlineEarly] __init(int v) { return vector<T,N>(T(v)); }
    [OverloadRank(-1)]
    [__unsafeForceInlineEarly] __init(float v) { return vector<T,N>(T(v)); }

The correct code should be assigning to "this",

__init(...) { this = vector<T,N>(T(v)); }

We may find more cases like this once we have a compiler error implemented.

jkwak-work avatar Mar 04 '24 22:03 jkwak-work

When I try to use "return;" inside of "__init()", like this,

__init()
{
    return;
}

it hits an error in a following condition, because "returnType" is a type of its own; not Void.

    void SemanticsStmtVisitor::visitReturnStmt(ReturnStmt *stmt)
    {
        auto function = getParentFunc();
        if (!stmt->expression)
        {
            if (function && !function->returnType.equals(m_astBuilder->getVoidType()))
            {
                getSink()->diagnose(stmt, Diagnostics::returnNeedsExpression);
            }
        }

The error message is

'return' should have an expression.

, which is not the case for __init.

The related code is in the following function,

    void SemanticsDeclHeaderVisitor::visitConstructorDecl(ConstructorDecl* decl)
    {
        // We need to compute the result tyep for this declaration,
        // since it wasn't filled in for us.
        decl->returnType.type = findResultTypeForConstructorDecl(decl);

        checkCallableDeclCommon(decl);
    }

I tried to replace it to

        decl->returnType.type = m_astBuilder->getVoidType();

And it breaks bunch. The error message looks like following,

core.meta.slang(986): error 30019: expected an expression of type 'half', got 'void'
    static const half maxValue = half(65504);

It seems that __init is expected to return a type of its own type.

We may need to make an exception for the constructor when we check the return statement, "SemanticsStmtVisitor::visitReturnStmt()".

jkwak-work avatar Mar 10 '24 20:03 jkwak-work