vm.hpp 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. /*=============================================================================
  2. Copyright (c) 2001-2011 Joel de Guzman
  3. Distributed under the Boost Software License, Version 1.0. (See accompanying
  4. file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  5. =============================================================================*/
  6. #if !defined(BOOST_SPIRIT_CONJURE_VM_HPP)
  7. #define BOOST_SPIRIT_CONJURE_VM_HPP
  8. #include <vector>
  9. namespace client
  10. {
  11. ///////////////////////////////////////////////////////////////////////////
  12. // The Virtual Machine
  13. ///////////////////////////////////////////////////////////////////////////
  14. enum byte_code
  15. {
  16. op_neg, // negate the top stack entry
  17. op_add, // add top two stack entries
  18. op_sub, // subtract top two stack entries
  19. op_mul, // multiply top two stack entries
  20. op_div, // divide top two stack entries
  21. op_not, // boolean negate the top stack entry
  22. op_eq, // compare the top two stack entries for ==
  23. op_neq, // compare the top two stack entries for !=
  24. op_lt, // compare the top two stack entries for <
  25. op_lte, // compare the top two stack entries for <=
  26. op_gt, // compare the top two stack entries for >
  27. op_gte, // compare the top two stack entries for >=
  28. op_and, // logical and top two stack entries
  29. op_or, // logical or top two stack entries
  30. op_load, // load a variable
  31. op_store, // store a variable
  32. op_int, // push constant integer into the stack
  33. op_true, // push constant 0 into the stack
  34. op_false, // push constant 1 into the stack
  35. op_jump_if, // jump to a relative position in the code if top stack
  36. // evaluates to false
  37. op_jump, // jump to a relative position in the code
  38. op_stk_adj, // adjust the stack (for args and locals)
  39. op_call, // function call
  40. op_return // return from function
  41. };
  42. class vmachine
  43. {
  44. public:
  45. vmachine(unsigned stackSize = 4096)
  46. : stack(stackSize)
  47. {
  48. }
  49. int execute(std::vector<int> const& code)
  50. {
  51. return execute(code, code.begin(), stack.begin());
  52. }
  53. std::vector<int> const& get_stack() const { return stack; };
  54. std::vector<int>& get_stack() { return stack; };
  55. private:
  56. int execute(
  57. std::vector<int> const& code // the program code
  58. , std::vector<int>::const_iterator pc // program counter
  59. , std::vector<int>::iterator frame_ptr // start of arguments and locals
  60. );
  61. std::vector<int> stack;
  62. };
  63. }
  64. #endif