codeobject.h 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  1. #pragma once
  2. #include "obj.h"
  3. #include "error.h"
  4. namespace pkpy{
  5. enum NameScope { NAME_LOCAL, NAME_GLOBAL, NAME_GLOBAL_UNKNOWN };
  6. enum Opcode: uint8_t {
  7. #define OPCODE(name) OP_##name,
  8. #include "opcodes.h"
  9. #undef OPCODE
  10. };
  11. inline const char* OP_NAMES[] = {
  12. #define OPCODE(name) #name,
  13. #include "opcodes.h"
  14. #undef OPCODE
  15. };
  16. struct Bytecode{
  17. uint8_t op;
  18. uint16_t arg;
  19. };
  20. enum class CodeBlockType {
  21. NO_BLOCK,
  22. FOR_LOOP,
  23. WHILE_LOOP,
  24. CONTEXT_MANAGER,
  25. TRY_EXCEPT,
  26. };
  27. inline const uint8_t BC_NOARG = 0;
  28. inline const int BC_KEEPLINE = -1;
  29. struct CodeBlock {
  30. CodeBlockType type;
  31. int parent; // parent index in blocks
  32. int base_stack_size; // this is used for exception handling
  33. int start; // start index of this block in codes, inclusive
  34. int end; // end index of this block in codes, exclusive
  35. int end2; // ...
  36. CodeBlock(CodeBlockType type, int parent, int base_stack_size, int start):
  37. type(type), parent(parent), base_stack_size(base_stack_size), start(start), end(-1), end2(-1) {}
  38. int get_break_end() const{
  39. if(end2 != -1) return end2;
  40. return end;
  41. }
  42. };
  43. struct CodeObject;
  44. struct FuncDecl;
  45. using CodeObject_ = std::shared_ptr<CodeObject>;
  46. using FuncDecl_ = std::shared_ptr<FuncDecl>;
  47. struct CodeObject {
  48. std::shared_ptr<SourceData> src;
  49. Str name;
  50. bool is_generator = false;
  51. std::vector<Bytecode> codes;
  52. std::vector<int> iblocks; // block index for each bytecode
  53. std::vector<int> lines; // line number for each bytecode
  54. List consts;
  55. std::vector<StrName> varnames; // local variables
  56. NameDictInt varnames_inv;
  57. std::vector<CodeBlock> blocks = { CodeBlock(CodeBlockType::NO_BLOCK, -1, 0, 0) };
  58. NameDictInt labels;
  59. std::vector<FuncDecl_> func_decls;
  60. const CodeBlock& _get_block_codei(int codei) const{
  61. return blocks[iblocks[codei]];
  62. }
  63. CodeObject(std::shared_ptr<SourceData> src, const Str& name);
  64. void _gc_mark() const;
  65. };
  66. struct FuncDecl {
  67. struct KwArg {
  68. int index; // index in co->varnames
  69. StrName key; // name of this argument
  70. PyObject* value; // default value
  71. };
  72. CodeObject_ code; // code object of this function
  73. std::vector<int> args; // indices in co->varnames
  74. std::vector<KwArg> kwargs; // indices in co->varnames
  75. int starred_arg = -1; // index in co->varnames, -1 if no *arg
  76. int starred_kwarg = -1; // index in co->varnames, -1 if no **kwarg
  77. bool nested = false; // whether this function is nested
  78. Str signature; // signature of this function
  79. Str docstring; // docstring of this function
  80. bool is_simple;
  81. NameDictInt kw_to_index;
  82. void add_kwarg(int index, StrName key, PyObject* value){
  83. kw_to_index.set(key, index);
  84. kwargs.push_back({index, key, value});
  85. }
  86. void _gc_mark() const;
  87. };
  88. struct UserData{
  89. char data[12];
  90. bool empty;
  91. UserData(): empty(true) {}
  92. template<typename T>
  93. UserData(T t): empty(false){
  94. static_assert(std::is_trivially_copyable_v<T>);
  95. static_assert(sizeof(T) <= sizeof(data));
  96. memcpy(data, &t, sizeof(T));
  97. }
  98. template <typename T>
  99. T get() const{
  100. static_assert(std::is_trivially_copyable_v<T>);
  101. static_assert(sizeof(T) <= sizeof(data));
  102. #if PK_DEBUG_EXTRA_CHECK
  103. PK_ASSERT(!empty);
  104. #endif
  105. return reinterpret_cast<const T&>(data);
  106. }
  107. };
  108. struct NativeFunc {
  109. NativeFuncC f;
  110. // old style argc-based call
  111. int argc;
  112. // new style decl-based call
  113. FuncDecl_ decl;
  114. UserData _userdata;
  115. void set_userdata(UserData data) {
  116. if(!_userdata.empty && !data.empty){
  117. // override is not supported
  118. throw std::runtime_error("userdata already set");
  119. }
  120. _userdata = data;
  121. }
  122. NativeFunc(NativeFuncC f, int argc, bool method);
  123. NativeFunc(NativeFuncC f, FuncDecl_ decl);
  124. void check_size(VM* vm, ArgsView args) const;
  125. PyObject* call(VM* vm, ArgsView args) const;
  126. };
  127. struct Function{
  128. FuncDecl_ decl;
  129. PyObject* _module; // weak ref
  130. PyObject* _class; // weak ref
  131. NameDict_ _closure;
  132. explicit Function(FuncDecl_ decl, PyObject* _module, PyObject* _class, NameDict_ _closure):
  133. decl(decl), _module(_module), _class(_class), _closure(_closure) {}
  134. };
  135. template<>
  136. struct Py_<Function> final: PyObject {
  137. Function _value;
  138. template<typename... Args>
  139. Py_(Type type, Args&&... args): PyObject(type), _value(std::forward<Args>(args)...) {
  140. // _enable_instance_dict();
  141. }
  142. void _obj_gc_mark() override {
  143. _value.decl->_gc_mark();
  144. if(_value._closure != nullptr) gc_mark_namedict(*_value._closure);
  145. }
  146. void* _value_ptr() override {
  147. return &_value;
  148. }
  149. };
  150. template<>
  151. struct Py_<NativeFunc> final: PyObject {
  152. NativeFunc _value;
  153. template<typename... Args>
  154. Py_(Type type, Args&&... args): PyObject(type), _value(std::forward<Args>(args)...) {
  155. // _enable_instance_dict();
  156. }
  157. void _obj_gc_mark() override {
  158. if(_value.decl != nullptr){
  159. _value.decl->_gc_mark();
  160. }
  161. }
  162. void* _value_ptr() override {
  163. return &_value;
  164. }
  165. };
  166. template<typename T>
  167. T lambda_get_userdata(PyObject** p){
  168. if(p[-1] != PY_NULL) return PK_OBJ_GET(NativeFunc, p[-1])._userdata.get<T>();
  169. else return PK_OBJ_GET(NativeFunc, p[-2])._userdata.get<T>();
  170. }
  171. } // namespace pkpy