codeobject.h 5.5 KB

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