From 897456c2f6da6a7352365c409db7510f83b9bceb Mon Sep 17 00:00:00 2001 From: blueloveTH Date: Thu, 27 Apr 2023 15:39:21 +0800 Subject: [PATCH] fix https://github.com/blueloveTH/pocketpy/issues/39 --- python/builtins.py | 10 +++++++++- src/ceval.h | 4 ++++ src/compiler.h | 13 +++++++++++++ src/opcodes.h | 1 + src/str.h | 1 + 5 files changed, 28 insertions(+), 1 deletion(-) diff --git a/python/builtins.py b/python/builtins.py index 3fbdfce5..32e05ca2 100644 --- a/python/builtins.py +++ b/python/builtins.py @@ -203,4 +203,12 @@ class staticmethod: return self.f(*args) def type@__repr__(self): - return "" \ No newline at end of file + return "" + +def help(obj): + if hasattr(obj, '__func__'): + obj = obj.__func__ + if hasattr(obj, '__doc__'): + print(obj.__doc__) + else: + print("No docstring found") diff --git a/src/ceval.h b/src/ceval.h index f3242ae9..20c2fb2e 100644 --- a/src/ceval.h +++ b/src/ceval.h @@ -543,6 +543,10 @@ __NEXT_STEP:; _error(StrName(byte.arg), msg); } DISPATCH(); TARGET(RE_RAISE) _raise(); DISPATCH(); + /*****************************************/ + TARGET(SETUP_DOCSTRING) + TOP()->attr().set(__doc__, co_consts[byte.arg]); + DISPATCH(); #if !PK_ENABLE_COMPUTED_GOTO #if DEBUG_EXTRA_CHECK default: throw std::runtime_error(fmt(OP_NAMES[byte.op], " is not implemented")); diff --git a/src/compiler.h b/src/compiler.h index 799f1cea..f1928a6b 100644 --- a/src/compiler.h +++ b/src/compiler.h @@ -922,7 +922,20 @@ __SUBSCR_END: } compile_block_body(); pop_context(); + + PyObject* docstring = nullptr; + if(decl->code->codes.size()>=2 && decl->code->codes[0].op == OP_LOAD_CONST && decl->code->codes[1].op == OP_POP_TOP){ + PyObject* c = decl->code->consts[decl->code->codes[0].arg]; + if(is_type(c, vm->tp_str)){ + decl->code->codes[0].op = OP_NO_OP; + decl->code->codes[1].op = OP_NO_OP; + docstring = c; + } + } ctx()->emit(OP_LOAD_FUNCTION, ctx()->add_func_decl(decl), prev().line); + if(docstring != nullptr){ + ctx()->emit(OP_SETUP_DOCSTRING, ctx()->add_const(docstring), prev().line); + } // add decorators for(auto it=decorators.rbegin(); it!=decorators.rend(); ++it){ (*it)->emit(ctx()); diff --git a/src/opcodes.h b/src/opcodes.h index 1cfce753..8788624b 100644 --- a/src/opcodes.h +++ b/src/opcodes.h @@ -110,4 +110,5 @@ OPCODE(EXCEPTION_MATCH) OPCODE(RAISE) OPCODE(RE_RAISE) /**************************/ +OPCODE(SETUP_DOCSTRING) #endif \ No newline at end of file diff --git a/src/str.h b/src/str.h index 63dac092..fc2de107 100644 --- a/src/str.h +++ b/src/str.h @@ -394,6 +394,7 @@ const StrName __set__ = StrName::get("__set__"); const StrName __getattr__ = StrName::get("__getattr__"); const StrName __setattr__ = StrName::get("__setattr__"); const StrName __call__ = StrName::get("__call__"); +const StrName __doc__ = StrName::get("__doc__"); const StrName m_eval = StrName::get("eval"); const StrName m_self = StrName::get("self");