lcompilers / lpython

Python compiler
https://lpython.org/
Other
1.5k stars 157 forks source link

dataclass `__post_init__` produces bogus `Inheritance error` #1927

Open rebcabin opened 1 year ago

rebcabin commented 1 year ago

The following works in ordinary CPython

@dataclass
class StringIO:
    _buf     : str
    _0cursor : int = 0
    _len     : int = 0

    def __post_init__(self):
        self._len = len(self._buf)

if __name__ == '__main__':
    integer_asr : str = '(Integer 4 [])'
    test_dude   : StringIO = StringIO(integer_asr)
    assert test_dude._buf == integer_asr
    assert test_dude._len == len(integer_asr)

The equivalent in LPython produces a traceback for Inheritance Error

@dataclass
class StringIO:
    _buf     : str
    _0cursor : i32 = i32(0)
    _len     : i32 = i32(0)

    def __post_init__(self):
        self._len(self._buf)

if __name__ == '__main__':
    integer_asr : str = '(Integer 4 [])'
    test_dude   : StringIO = StringIO(integer_asr, 0, len(integer_asr))
    assert test_dude._buf == integer_asr
    assert test_dude._len == len(integer_asr)

produces

└─(15:02:09 on brian-lasr ✹ ✭)──> ~/CLionProjects/lpython/src/bin/lpython lasr_lexer.py                                                               1 ↵ ──(Fri,Jun16)─┘
Internal Compiler Error: Unhandled exception
Traceback (most recent call last):
  File "/Users/brian/CLionProjects/lpython/src/bin/lpython.cpp", line 1828
    err = compile_python_to_object_file(arg_file, tmp_o, runtime_library_dir,
  File "/Users/brian/CLionProjects/lpython/src/bin/lpython.cpp", line 783
    r1 = LCompilers::LPython::python_ast_to_asr(al, lm, *ast, diagnostics, compiler_options,
  File "/Users/brian/CLionProjects/lpython/src/lpython/semantics/python_ast_to_asr.cpp", line 7413
    diagnostics.diagnostics.push_back(e.d);
  File "/Users/brian/CLionProjects/lpython/src/lpython/semantics/python_ast_to_asr.cpp", line 4411
    // We skip this in the SymbolTable visitor, but visit it in the BodyVisitor
  File "/Users/brian/CLionProjects/lpython/src/lpython/semantics/python_ast_to_asr.cpp", line 3748
    /* a_symtab */ current_scope,
  File "/Users/brian/CLionProjects/lpython/src/lpython/python_ast.h", line 1883
    void visit_stmt(const stmt_t &b) { visit_stmt_t(b, self()); }
  File "/Users/brian/CLionProjects/lpython/src/lpython/python_ast.h", line 1752
    case stmtType::AsyncFunctionDef: { v.visit_AsyncFunctionDef((const AsyncFunctionDef_t &)x); return; }
  File "/Users/brian/CLionProjects/lpython/src/lpython/semantics/python_ast_to_asr.cpp", line 2989
    throw SemanticError("Inheritance in classes isn't supported yet.",
  File "/Users/brian/CLionProjects/lpython/src/lpython/semantics/python_ast_to_asr.cpp", line 2783
    }
AssertFailed: AST::is_a<AST::AnnAssign_t>(*x.m_body[i])
Thirumalai-Shaktivel commented 1 year ago

Yup, we need to support function definition inside the dataclass or class definition. Thanks for reporting this!